diff --git a/AnkiDroid/src/main/java/com/ichi2/anki/Statistics.kt b/AnkiDroid/src/main/java/com/ichi2/anki/Statistics.kt index d9c98de70c95..055ee4038a10 100644 --- a/AnkiDroid/src/main/java/com/ichi2/anki/Statistics.kt +++ b/AnkiDroid/src/main/java/com/ichi2/anki/Statistics.kt @@ -378,7 +378,7 @@ class Statistics : NavigationDrawerActivity(), DeckSelectionListener, SubtitleLi private fun createChart() { val statisticsActivity = requireActivity() as Statistics val taskHandler = statisticsActivity.taskHandler - statisticsJob = viewLifecycleOwner.catchingLifecycleScope(requireActivity()) { + statisticsJob = catchingLifecycleScope { taskHandler.createChart(getChartTypeFromPosition(mSectionNumber), mProgressBar, mChart) } } @@ -453,7 +453,7 @@ class Statistics : NavigationDrawerActivity(), DeckSelectionListener, SubtitleLi private fun createStatisticOverview() { val handler = (requireActivity() as Statistics).taskHandler - statisticsJob = catchingLifecycleScope(requireActivity(), "createStatisticOverview failed with error") { + statisticsJob = catchingLifecycleScope("createStatisticOverview failed with error") { handler.createStatisticsOverview(mWebView, mProgressBar) } } diff --git a/AnkiDroid/src/main/java/com/ichi2/async/CoroutineHelpers.kt b/AnkiDroid/src/main/java/com/ichi2/async/CoroutineHelpers.kt index df9c1982d241..75480e6768c0 100644 --- a/AnkiDroid/src/main/java/com/ichi2/async/CoroutineHelpers.kt +++ b/AnkiDroid/src/main/java/com/ichi2/async/CoroutineHelpers.kt @@ -20,6 +20,7 @@ package com.ichi2.async import android.app.Activity +import androidx.fragment.app.Fragment import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.coroutineScope import com.ichi2.anki.CrashReportService @@ -30,7 +31,7 @@ import kotlinx.coroutines.Job import kotlinx.coroutines.launch import timber.log.Timber -/* +/** * Launch a job that catches any uncaught errors, informs the user and prints it to Log. * Errors from the backend contain localized text that is often suitable to show to the user as-is. * Other errors should ideally be handled in the block. @@ -51,3 +52,16 @@ fun LifecycleOwner.catchingLifecycleScope( CrashReportService.sendExceptionReport(e, activity::class.java.simpleName) } } + +/** + * @see [LifecycleOwner.catchingLifecycleScope] + */ +fun Fragment.catchingLifecycleScope( + errorMessage: String? = null, + block: suspend CoroutineScope.() -> Unit +) = (this as LifecycleOwner).catchingLifecycleScope(requireActivity(), errorMessage, block) + +fun Activity.catchingLifecycleScope( + errorMessage: String? = null, + block: suspend CoroutineScope.() -> Unit +) = (this as LifecycleOwner).catchingLifecycleScope(this, errorMessage, block)