Fix an issue with deleting changes upon device rotation

This commit is contained in:
William Brawner 2020-10-05 20:43:56 -07:00
parent 1affb7069a
commit 0e7cdfa2b5
4 changed files with 23 additions and 7 deletions

View file

@ -1,5 +1,6 @@
package com.wbrawner.simplemarkdown.utility
import android.util.Log
import kotlin.reflect.KProperty
class errorHandlerImpl {

View file

@ -95,8 +95,11 @@ class EditFragment : Fragment(), ViewPagerPage, CoroutineScope {
false
}
markdownEditor?.setText(viewModel.markdownUpdates.value)
viewModel.originalMarkdown.observe(viewLifecycleOwner, Observer {
markdownEditor?.setText(it)
viewModel.editorActions.observe(viewLifecycleOwner, Observer {
if (it.consumed.getAndSet(true)) return@Observer
if (it is MarkdownViewModel.EditorAction.Load) {
markdownEditor?.setText(it.markdown)
}
})
launch {
val enableReadability = withContext(Dispatchers.IO) {

View file

@ -252,7 +252,7 @@ class MainFragment : Fragment(), ActivityCompat.OnRequestPermissionsResultCallba
}
private fun promptSaveOrDiscardChanges() {
if (viewModel.originalMarkdown.value == viewModel.markdownUpdates.value) {
if (viewModel.shouldPromptSave()) {
viewModel.reset("Untitled.md")
PreferenceManager.getDefaultSharedPreferences(requireContext()).edit {
remove(getString(R.string.pref_key_autosave_uri))

View file

@ -9,15 +9,18 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.FileInputStream
import java.io.Reader
import java.util.concurrent.atomic.AtomicBoolean
class MarkdownViewModel : ViewModel() {
val fileName = MutableLiveData<String>("Untitled.md")
val markdownUpdates = MutableLiveData<String>()
val originalMarkdown = MutableLiveData<String>()
val editorActions = MutableLiveData<EditorAction>()
val uri = MutableLiveData<Uri>()
private val isDirty = AtomicBoolean(false)
fun updateMarkdown(markdown: String?) {
this.markdownUpdates.postValue(markdown ?: "")
isDirty.set(true)
}
suspend fun load(context: Context, uri: Uri?): Boolean {
@ -32,7 +35,8 @@ class MarkdownViewModel : ViewModel() {
// If we don't get anything back, then we can assume that reading the file failed
return@withContext false
}
originalMarkdown.postValue(content)
isDirty.set(false)
editorActions.postValue(EditorAction.Load(content))
markdownUpdates.postValue(content)
this@MarkdownViewModel.fileName.postValue(fileName)
this@MarkdownViewModel.uri.postValue(uri)
@ -66,7 +70,15 @@ class MarkdownViewModel : ViewModel() {
fun reset(untitledFileName: String) {
fileName.postValue(untitledFileName)
originalMarkdown.postValue("")
markdownUpdates.postValue("")
isDirty.set(false)
}
fun shouldPromptSave() = isDirty.get()
sealed class EditorAction {
val consumed = AtomicBoolean(false)
data class Load(val markdown: String) : EditorAction()
}
}