From 0b293d08ccb4ebf8f654f45ff7c1e4c6d336febc Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Tue, 21 Sep 2021 11:15:32 +0100 Subject: [PATCH] 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 --- ...rSettingsNotificationPreferenceFragment.kt | 26 ++++++++++++++----- 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/vector/src/main/java/im/vector/app/features/settings/notifications/VectorSettingsNotificationPreferenceFragment.kt b/vector/src/main/java/im/vector/app/features/settings/notifications/VectorSettingsNotificationPreferenceFragment.kt index c57ce2a86a..0a123b8281 100644 --- a/vector/src/main/java/im/vector/app/features/settings/notifications/VectorSettingsNotificationPreferenceFragment.kt +++ b/vector/src/main/java/im/vector/app/features/settings/notifications/VectorSettingsNotificationPreferenceFragment.kt @@ -43,6 +43,7 @@ import im.vector.app.features.settings.VectorPreferences import im.vector.app.features.settings.VectorSettingsBaseFragment import im.vector.app.features.settings.VectorSettingsFragmentInteractionListener import im.vector.app.push.fcm.FcmHelper +import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import org.matrix.android.sdk.api.extensions.tryOrNull import org.matrix.android.sdk.api.pushrules.RuleIds @@ -141,15 +142,12 @@ class VectorSettingsNotificationPreferenceFragment @Inject constructor( val pref = VectorSwitchPreference(requireContext()) pref.title = resources.getString(R.string.settings_notification_emails_enable_for_email, emailPid.email) pref.isChecked = pusher != null - pref.setOnPreferenceChangeListener { _, newValue -> - if (newValue as Boolean) { + pref.setTransactionalSwitchChangeListener(lifecycleScope) { isChecked -> + if (isChecked) { pushManager.registerEmailForPush(emailPid.email) } else { - lifecycleScope.launch { - pushManager.unregisterEmailPusher(emailPid.email) - } + pushManager.unregisterEmailPusher(emailPid.email) } - true } 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 + } +}