handling errors when enabling/disabling email notifications

- Extracts out a transactional switch helper to handle reverting the switch back to its original state if an error occurs
- Reuses existing toast message for unknown error
- Does not include the isAdded to the async callback as the couroutine is tied to the fragment lifecycle scope
This commit is contained in:
Adam Brown 2021-09-21 11:15:32 +01:00
parent 410cf5c062
commit 0b293d08cc
1 changed files with 20 additions and 6 deletions

View File

@ -43,6 +43,7 @@ import im.vector.app.features.settings.VectorPreferences
import im.vector.app.features.settings.VectorSettingsBaseFragment import im.vector.app.features.settings.VectorSettingsBaseFragment
import im.vector.app.features.settings.VectorSettingsFragmentInteractionListener import im.vector.app.features.settings.VectorSettingsFragmentInteractionListener
import im.vector.app.push.fcm.FcmHelper import im.vector.app.push.fcm.FcmHelper
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import org.matrix.android.sdk.api.extensions.tryOrNull import org.matrix.android.sdk.api.extensions.tryOrNull
import org.matrix.android.sdk.api.pushrules.RuleIds import org.matrix.android.sdk.api.pushrules.RuleIds
@ -141,16 +142,13 @@ class VectorSettingsNotificationPreferenceFragment @Inject constructor(
val pref = VectorSwitchPreference(requireContext()) val pref = VectorSwitchPreference(requireContext())
pref.title = resources.getString(R.string.settings_notification_emails_enable_for_email, emailPid.email) pref.title = resources.getString(R.string.settings_notification_emails_enable_for_email, emailPid.email)
pref.isChecked = pusher != null pref.isChecked = pusher != null
pref.setOnPreferenceChangeListener { _, newValue -> pref.setTransactionalSwitchChangeListener(lifecycleScope) { isChecked ->
if (newValue as Boolean) { if (isChecked) {
pushManager.registerEmailForPush(emailPid.email) pushManager.registerEmailForPush(emailPid.email)
} else { } else {
lifecycleScope.launch {
pushManager.unregisterEmailPusher(emailPid.email) pushManager.unregisterEmailPusher(emailPid.email)
} }
} }
true
}
category.addPreference(pref) category.addPreference(pref)
} }
} }
@ -386,3 +384,19 @@ class VectorSettingsNotificationPreferenceFragment @Inject constructor(
} }
} }
} }
private fun SwitchPreference.setTransactionalSwitchChangeListener(scope: CoroutineScope, transaction: suspend (Boolean) -> Unit) {
val originalState = this.isChecked
this.setOnPreferenceChangeListener { switchPreference, isChecked ->
scope.launch {
try {
transaction(isChecked as Boolean)
} catch (failure: Throwable) {
require(switchPreference is SwitchPreference)
switchPreference.isChecked = originalState
Toast.makeText(switchPreference.context, R.string.unknown_error, Toast.LENGTH_SHORT).show()
}
}
true
}
}