From b9b20d7d945add9fda4b9bcb71b161d639576122 Mon Sep 17 00:00:00 2001 From: David Allison <62114487+david-allison@users.noreply.github.com> Date: Wed, 8 Jan 2025 02:28:25 +0000 Subject: [PATCH] improvement: use `repeatOnLifecycle` review request --- .../main/java/com/ichi2/anki/AnkiActivity.kt | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/AnkiDroid/src/main/java/com/ichi2/anki/AnkiActivity.kt b/AnkiDroid/src/main/java/com/ichi2/anki/AnkiActivity.kt index 94c741781401..bc89e7d2a9cf 100644 --- a/AnkiDroid/src/main/java/com/ichi2/anki/AnkiActivity.kt +++ b/AnkiDroid/src/main/java/com/ichi2/anki/AnkiActivity.kt @@ -43,7 +43,9 @@ import androidx.core.app.NotificationCompat import androidx.core.app.PendingIntentCompat import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment +import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope +import androidx.lifecycle.repeatOnLifecycle import com.google.android.material.color.MaterialColors import com.google.android.material.snackbar.Snackbar import com.ichi2.anim.ActivityTransitionAnimation @@ -725,14 +727,16 @@ open class AnkiActivity : // TODO: Move this to an extension method once we have context parameters protected fun Flow.launchCollectionInLifecycleScope(block: suspend (T) -> Unit) { lifecycleScope.launch { - this@launchCollectionInLifecycleScope.collect { - if (isRobolectric) { - // hack: lifecycleScope/runOnUiThread do not handle our - // test dispatcher overriding both IO and Main - // in tests, waitForAsyncTasksToComplete may be required. - HandlerUtils.postOnNewHandler { runBlocking { block(it) } } - } else { - block(it) + lifecycle.repeatOnLifecycle(Lifecycle.State.RESUMED) { + this@launchCollectionInLifecycleScope.collect { + if (isRobolectric) { + // hack: lifecycleScope/runOnUiThread do not handle our + // test dispatcher overriding both IO and Main + // in tests, waitForAsyncTasksToComplete may be required. + HandlerUtils.postOnNewHandler { runBlocking { block(it) } } + } else { + block(it) + } } } }