Просмотр исходного кода

fix: restore backup JobCancellationException on Activity relaunch

Move restore coroutine from rememberCoroutineScope() to viewModelScope
so it survives Activity recreation during config changes.
HapeLee 5 месяцев назад
Родитель
Сommit
b408ba580a

+ 15 - 9
app/src/main/java/io/legado/app/ui/config/backupConfig/BackupConfigScreen.kt

@@ -169,18 +169,24 @@ fun BackupConfigScreen(
         uri?.let {
             showLoadingDialog = true
             loadingText = context.getString(R.string.on_restore)
-            scope.launch {
-                try {
-                    Restore.restore(context, uri)
+            viewModel.restore(
+                context = context,
+                uri = uri,
+                onSuccess = {
                     showLoadingDialog = false
-                    snackbarHostState.showSnackbar(context.getString(R.string.restore_success))
-                } catch (e: Exception) {
+                    scope.launch {
+                        snackbarHostState.showSnackbar(context.getString(R.string.restore_success))
+                    }
+                },
+                onError = { error ->
                     showLoadingDialog = false
-                    snackbarHostState.showSnackbar(
-                        context.getString(R.string.restore_fail_with_error, e.localizedMessage)
-                    )
+                    scope.launch {
+                        snackbarHostState.showSnackbar(
+                            context.getString(R.string.restore_fail_with_error, error)
+                        )
+                    }
                 }
-            }
+            )
         }
     }
 

+ 18 - 0
app/src/main/java/io/legado/app/ui/config/backupConfig/BackupConfigViewModel.kt

@@ -1,10 +1,13 @@
 package io.legado.app.ui.config.backupConfig
 
+import android.content.Context
+import android.net.Uri
 import androidx.lifecycle.ViewModel
 import androidx.lifecycle.viewModelScope
 import io.legado.app.R
 import io.legado.app.domain.usecase.WebDavBackupUseCase
 import io.legado.app.help.storage.Backup
+import io.legado.app.help.storage.Restore
 import kotlinx.coroutines.Dispatchers
 import kotlinx.coroutines.launch
 import kotlinx.coroutines.withContext
@@ -83,4 +86,19 @@ class BackupConfigViewModel(
         }
     }
 
+    fun restore(context: Context, uri: Uri, onSuccess: () -> Unit, onError: (String) -> Unit) {
+        viewModelScope.launch(Dispatchers.IO) {
+            try {
+                Restore.restore(context, uri)
+                withContext(Dispatchers.Main) {
+                    onSuccess()
+                }
+            } catch (e: Exception) {
+                withContext(Dispatchers.Main) {
+                    onError(e.localizedMessage ?: appCtx.getString(R.string.restore_error))
+                }
+            }
+        }
+    }
+
 }