Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
}
like image 451
tperraut Avatar asked Nov 06 '19 15:11

tperraut


1 Answers

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 {
    [email protected] { /* Do nothing */ }
}

Hope it helps

like image 51
tperraut Avatar answered Oct 18 '22 05:10

tperraut