How to spot where “Job was cancelled” exception comes from when all your coroutines are already wrapped with a CouroutineExceptionHandler?

六眼飞鱼酱① 提交于 2021-02-08 21:57:49

问题


I read all the kotlinx UI docs and implement a ScopedActivity like described there (see the code below).

In my ScopedActivity implementation, I also add a CouroutineExceptionHandler and despite that I pass my exception handler to all my coroutines, my users are experiencing crashes and the only info I get in the stacktrace is "Job was cancelled".

I searched for a couple of days now but I did not find a solution and my users are still randomly crashing but I do not understand why...

Here is my ScopedActivity implementation

abstract class ScopedActivity : BaseActivity(), CoroutineScope by MainScope() {

    val errorHandler by lazy { CoroutineExceptionHandler { _, throwable -> onError(throwable) } }

    open fun onError(e: Throwable? = null) {
        e ?: return
        Timber.i(e)
    }

    override fun onDestroy() {
        super.onDestroy()
        cancel()
    }
}

Here is an example of an activity implementing it :

class ManageBalanceActivity : ScopedActivity() {

    @Inject
    lateinit var viewModel: ManageBalanceViewModel

    private var stateJob: Job? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_manage_balance)
        AndroidInjection.inject(this)

        init()
    }

    private fun init() {
        SceneManager.create(
            SceneCreator.with(this)
                .add(Scene.MAIN, R.id.activity_manage_balance_topup_view)
                .add(Scene.MAIN, R.id.activity_manage_balance_topup_bt)
                .add(Scene.SPINNER, R.id.activity_manage_balance_spinner)
                .add(Scene.SPINNER, R.id.activity_manage_balance_info_text)
                .add(Scene.PLACEHOLDER, R.id.activity_manage_balance_error_text)
                .first(Scene.SPINNER)
        )

        // Setting some onClickListeners ...
        bindViewModel()
    }

    private fun bindViewModel() {
        showProgress()
        stateJob = launch(errorHandler) {
            viewModel.state.collect { manageState(it) }
        }
    }

    private fun manageState(state: ManageBalanceState) = when (state) {
        is ManageBalanceState.NoPaymentMethod -> viewModel.navigateToManagePaymentMethod()
        is ManageBalanceState.HasPaymentMethod -> onPaymentMethodAvailable(state.balance)
    }

    private fun onPaymentMethodAvailable(balance: Cash) {
        toolbarTitle.text = formatCost(balance)
        activity_manage_balance_topup_view.currency = balance.currency
        SceneManager.scene(this, Scene.MAIN)
    }

    override fun onError(e: Throwable?) {
        super.onError(e)
        when (e) {
            is NotLoggedInException -> loadErrorScene(R.string.error_pls_signin)
            else -> loadErrorScene()
        }
    }

    private fun loadErrorScene(@StringRes textRes: Int = R.string.generic_error) {

   activity_manage_balance_error_text.setOnClickListener(this::reload)
        SceneManager.scene(this, Scene.PLACEHOLDER)
    }

    private fun reload(v: View) {
        v.setOnClickListener(null)
        stateJob.cancelIfPossible()
        bindViewModel()
    }

    private fun showProgress(@StringRes textRes: Int = R.string.please_wait_no_dot) {
        activity_manage_balance_info_text.setText(textRes)
        SceneManager.scene(this, Scene.SPINNER)
    }

    override fun onDestroy() {
        super.onDestroy()
        SceneManager.release(this)
    }
}
fun Job?.cancelIfPossible() {
    if (this?.isActive == true) cancel()
}

And here is the ViewModel

class ManageBalanceViewModel @Inject constructor(
    private val userGateway: UserGateway,
    private val paymentGateway: PaymentGateway,
    private val managePaymentMethodNavigator: ManagePaymentMethodNavigator
) {

    val state: Flow<ManageBalanceState>
        get() = paymentGateway.collectSelectedPaymentMethod()
            .combine(userGateway.collectLoggedUser()) { paymentMethod, user ->
                when (paymentMethod) {
                    null -> ManageBalanceState.NoPaymentMethod
                    else -> ManageBalanceState.HasPaymentMethod(Cash(user.creditBalance.toInt(), user.currency!!))
                }
            }
            .flowOn(Dispatchers.Default)

    // The navigator just do a startActivity with a clear task
    fun navigateToManagePaymentMethod() = managePaymentMethodNavigator.navigate(true)
}

回答1:


The issue was coming from Kotlin Flow trying to emit after cancellation and here are the extensions I created to remove the crashes from happening in production :

/**
 * Check if the channel is not closed and try to emit a value, catching [CancellationException] if the corresponding
 * has been cancelled. This extension is used in call callbackFlow.
 */
@ExperimentalCoroutinesApi
fun <E> SendChannel<E>.safeOffer(value: E): Boolean {
    if (isClosedForSend) return false
    return try {
        offer(value)
    } catch (e: CancellationException) {
        false
    }
}

/**
 * Terminal flow operator that collects the given flow with a provided [action] and catch [CancellationException]
 */
suspend inline fun <T> Flow<T>.safeCollect(crossinline action: suspend (value: T) -> Unit): Unit =
    collect { value ->
        try {
            action(value)
        } catch (e: CancellationException) {
            // Do nothing
        }
    }

/**
 * Terminal flow operator that [launches][launch] the [collection][collect] of the given flow in the [scope] and catch
 * [CancellationException]
 * It is a shorthand for `scope.launch { flow.safeCollect {} }`.
 */
fun <T> Flow<T>.safeLaunchIn(scope: CoroutineScope) = scope.launch {
    this@safeLaunchIn.safeCollect { /* Do nothing */ }
}

Hope it helps




回答2:


Most likely problems arise from the fact, that you are passing your coroutine exception handler (lets name it CEH) directly to your launch blocks. Those launch blocks are creating new Jobs (important - plain Jobs, not Supervisor ones), which become children of the Job in scope (MainScope in your Scoped Activity).

Ordinary Job will cancel all its children and itself, if any of its children raise an exception. CEH will not prevent this behaviour. It will get those exceptions and do, what it was told to do with them, but it will still not prevent cancellation of Job in scope and all its children. Most importantly IT WILL PROPAGATE EXCEPTION UP THE HIERARCHY TOO. TLDR - crash will not be handled.

In order for your CEH to do its job, you need to install it inside a context with SuperVisorJob (or NonCancellable one). SupervisorJob assumes, that you are supervising exceptions in its scope, so it will not cancel itself or its children, when exception is raised (however, if exception is not handled at all, it will propagate it anyway up the hierarchy).

For example in your ScopedActivity Scope:

abstract class ScopedActivity : BaseActivity(), CoroutineScope {

override val coroutineContext = Dispatchers.Main + SupervisorJob() + CoroutineExceptionHandler { _, error -> 
...
    }

If you really want, you may install CEH deeper in your coroutines hierarchy. It will look clumsy however and is not recommended practice:

launch {
    val supervisedJob = SupervisorJob(coroutineContext[Job])
    launch(supervisedJob + CEH) { 
        throw Exception() 
    }
    yield()
    println("I am still alive, exception was catched by CEH")
}

Above practice may however come useful if you want to launch some fire-and-forget non cancellable side effect:

launch(NonCancellable + CEH) {
        throw Exception()
    }


来源:https://stackoverflow.com/questions/58734114/how-to-spot-where-job-was-cancelled-exception-comes-from-when-all-your-corouti

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!