fix: restore backup JobCancellationException on Activity relaunch

Move restore coroutine from rememberCoroutineScope() to viewModelScope
so it survives Activity recreation during config changes.
This commit is contained in:
HapeLee
2026-05-29 22:53:57 +08:00
parent 288ffc2137
commit b408ba580a
2 changed files with 33 additions and 9 deletions
@@ -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)
)
}
}
}
)
}
}
@@ -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))
}
}
}
}
}