Repository: thundernest/k-9
Issue: Crash after removing account

**Describe the bug**
Deleting an account crashes the app

**To Reproduce**
Steps to reproduce the behavior:
1. Go *Account settings* screen for an account
2. Select *Remove account* from the menu
3. Crash?

**Environment**
- App version: 5.806 (28006) [F-Droid]
- Android version: 8.1.0
- Model: Lenovo Tabriz 8 plus (TB-8704X)


**Logs**
```
java.lang.IllegalStateException: Account f60b8bf7-bf95-4b55-81c8-83516da088e3 not found
	at com.fsck.k9.ui.settings.account.AccountSettingsViewModel.loadAccount(AccountSettingsViewModel.kt:51)
	at com.fsck.k9.ui.settings.account.AccountSettingsViewModel.access$loadAccount(AccountSettingsViewModel.kt:18)
	at com.fsck.k9.ui.settings.account.AccountSettingsViewModel$getAccount$1$1.invokeSuspend(AccountSettingsViewModel.kt:32)
	at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
	at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
	at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:571)
	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:678)
	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:665)
```

Originally reported here: https://forum.k9mail.app/t/crash-while-removing-account/3317


Changed files:
app/ui/legacy/src/main/java/com/fsck/k9/ui/settings/account/AccountSettingsViewModel.kt

diff --git a/app/ui/legacy/src/main/java/com/fsck/k9/ui/settings/account/AccountSettingsViewModel.kt b/app/ui/legacy/src/main/java/com/fsck/k9/ui/settings/account/AccountSettingsViewModel.kt
index 4a9b3b8cc..7930f383b 100644
--- a/app/ui/legacy/src/main/java/com/fsck/k9/ui/settings/account/AccountSettingsViewModel.kt
+++ b/app/ui/legacy/src/main/java/com/fsck/k9/ui/settings/account/AccountSettingsViewModel.kt
@@ -4,31 +4,34 @@ import androidx.lifecycle.LiveData
 import androidx.lifecycle.MutableLiveData
 import androidx.lifecycle.ViewModel
 import androidx.lifecycle.asLiveData
+import androidx.lifecycle.viewModelScope
 import com.fsck.k9.Account
 import com.fsck.k9.mailstore.FolderRepository
 import com.fsck.k9.mailstore.FolderType
 import com.fsck.k9.mailstore.RemoteFolder
 import com.fsck.k9.mailstore.SpecialFolderSelectionStrategy
 import com.fsck.k9.preferences.AccountManager
+import kotlinx.coroutines.CoroutineDispatcher
 import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.GlobalScope
 import kotlinx.coroutines.launch
 import kotlinx.coroutines.withContext
 
 class AccountSettingsViewModel(
     private val accountManager: AccountManager,
     private val folderRepository: FolderRepository,
-    private val specialFolderSelectionStrategy: SpecialFolderSelectionStrategy
+    private val specialFolderSelectionStrategy: SpecialFolderSelectionStrategy,
+    private val backgroundDispatcher: CoroutineDispatcher = Dispatchers.IO
 ) : ViewModel() {
     val accounts = accountManager.getAccountsFlow().asLiveData()
-    private val accountLiveData = MutableLiveData<Account>()
+    private var accountUuid: String? = null
+    private val accountLiveData = MutableLiveData<Account?>()
     private val foldersLiveData = MutableLiveData<RemoteFolderInfo>()
 
-    fun getAccount(accountUuid: String): LiveData<Account> {
-        if (accountLiveData.value == null) {
-
-            GlobalScope.launch(Dispatchers.Main) {
-                val account = withContext(Dispatchers.IO) {
+    fun getAccount(accountUuid: String): LiveData<Account?> {
+        if (this.accountUuid != accountUuid) {
+            this.accountUuid = accountUuid
+            viewModelScope.launch {
+                val account = withContext(backgroundDispatcher) {
                     loadAccount(accountUuid)
                 }
                 accountLiveData.value = account
@@ -43,13 +46,16 @@ class AccountSettingsViewModel(
      * doesn't support asynchronous preference loading.
      */
     fun getAccountBlocking(accountUuid: String): Account {
-        return accountLiveData.value ?: loadAccount(accountUuid).also {
-            accountLiveData.value = it
-        }
+        return accountLiveData.value
+            ?: loadAccount(accountUuid).also { account ->
+                this.accountUuid = accountUuid
+                accountLiveData.value = account
+            }
+            ?: error("Account $accountUuid not found")
     }
 
-    private fun loadAccount(accountUuid: String): Account {
-        return accountManager.getAccount(accountUuid) ?: error("Account $accountUuid not found")
+    private fun loadAccount(accountUuid: String): Account? {
+        return accountManager.getAccount(accountUuid)
     }
 
     fun getFolders(account: Account): LiveData<RemoteFolderInfo> {
@@ -61,8 +67,8 @@ class AccountSettingsViewModel(
     }
 
     private fun loadFolders(account: Account) {
-        GlobalScope.launch(Dispatchers.Main) {
-            val remoteFolderInfo = withContext(Dispatchers.IO) {
+        viewModelScope.launch {
+            val remoteFolderInfo = withContext(backgroundDispatcher) {
                 val folders = folderRepository.getRemoteFolders(account)
                 val automaticSpecialFolders = getAutomaticSpecialFolders(folders)
                 RemoteFolderInfo(folders, automaticSpecialFolders)