Fix issue with data loss upon device rotation

This commit is contained in:
William Brawner 2020-07-09 21:25:43 -07:00
parent d9afb67d44
commit 0ff680d648
3 changed files with 8 additions and 10 deletions

View file

@ -21,6 +21,7 @@ class MainActivity : AppCompatActivity(), ActivityCompat.OnRequestPermissionsRes
intent?.data?.let { intent?.data?.let {
launch { launch {
viewModel.load(this@MainActivity, it) viewModel.load(this@MainActivity, it)
intent?.data = null
} }
} }
} }

View file

@ -94,6 +94,7 @@ class EditFragment : Fragment(), ViewPagerPage, CoroutineScope {
} }
false false
} }
markdownEditor?.setText(viewModel.markdownUpdates.value)
viewModel.originalMarkdown.observe(viewLifecycleOwner, Observer { viewModel.originalMarkdown.observe(viewLifecycleOwner, Observer {
markdownEditor?.setText(it) markdownEditor?.setText(it)
}) })
@ -115,7 +116,6 @@ class EditFragment : Fragment(), ViewPagerPage, CoroutineScope {
} }
readabilityWatcher = null readabilityWatcher = null
} }
} }
} }

View file

@ -9,13 +9,9 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import java.io.FileInputStream import java.io.FileInputStream
import java.io.Reader import java.io.Reader
import kotlin.coroutines.CoroutineContext
class MarkdownViewModel : ViewModel() { class MarkdownViewModel : ViewModel() {
private val coroutineContext: CoroutineContext = Dispatchers.IO val fileName = MutableLiveData<String>("Untitled.md")
val fileName = MutableLiveData<String>().apply {
postValue("Untitled.md")
}
val markdownUpdates = MutableLiveData<String>() val markdownUpdates = MutableLiveData<String>()
val originalMarkdown = MutableLiveData<String>() val originalMarkdown = MutableLiveData<String>()
val uri = MutableLiveData<Uri>() val uri = MutableLiveData<Uri>()
@ -49,11 +45,12 @@ class MarkdownViewModel : ViewModel() {
return withContext(Dispatchers.IO) { return withContext(Dispatchers.IO) {
try { try {
val fileName = uri.getName(context) val fileName = uri.getName(context)
val outputStream = context.contentResolver.openOutputStream(uri, "rwt") context.contentResolver.openOutputStream(uri, "rwt")
?: return@withContext false ?.writer()
outputStream.writer().use { ?.use {
it.write(markdownUpdates.value ?: "") it.write(markdownUpdates.value ?: "")
} }
?: return@withContext false
this@MarkdownViewModel.fileName.postValue(fileName) this@MarkdownViewModel.fileName.postValue(fileName)
this@MarkdownViewModel.uri.postValue(uri) this@MarkdownViewModel.uri.postValue(uri)
true true