如何发现“作业被取消"的位置异常来自当您所有的协程已经用CouroutineExceptionHandler包装的时候? [英] How to spot where "Job was cancelled" exception comes from when all your coroutines are already wrapped with a CouroutineExceptionHandler?
问题描述
我阅读了所有 kotlinx UI文档并实现此处所述的ScopedActivity(请参见下面的代码).
I read all the kotlinx UI docs and implement a ScopedActivity like described there (see the code below).
在我的ScopedActivity实现中,我还添加了一个CouroutineExceptionHandler,尽管我将异常处理程序传递给我的所有协程,但我的用户正在崩溃,并且我在堆栈跟踪中获得的唯一信息是作业已取消".
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...
这是我的ScopedActivity实现
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()
}
这是ViewModel
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)
}
推荐答案
此问题来自Kotlin Flow,试图在取消后发出,这是我创建的扩展程序,用于消除生产中发生的崩溃:
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 */ }
}
希望有帮助
这篇关于如何发现“作业被取消"的位置异常来自当您所有的协程已经用CouroutineExceptionHandler包装的时候?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!