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 {
launch {
viewModel.load(this@MainActivity, it)
intent?.data = null
}
}
}

View file

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

View file

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