如何发现"Job was cancelled"异常来自哪里,当你所有的协程都已经用CouroutineExceptionHandler包装了?



我阅读了所有kotlinx UI文档,并实现了一个ScopedActivity,就像上面描述的那样(请参阅下面的代码(。

在我的ScopedActivity实现中,我还添加了一个CouroutineExceptionHandler,尽管我将异常处理程序传递给了所有的协同程序,但我的用户正在经历崩溃,我在堆栈中得到的唯一信息是"作业已取消"。

我搜索了几天,但我没有找到解决方案,我的用户仍然随机崩溃,但我不明白为什么。。。

这是我的ScopedActivity实现

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()
}
}

下面是一个实现它的活动示例:

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

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试图在取消后发出,以下是我创建的扩展,以消除生产中发生的崩溃:

/**
* 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 */ }
}

希望它能帮助

最有可能的问题是由于您将协程异常处理程序(让我们将其命名为CEH(直接传递到启动块。这些启动块正在创建新的作业(重要的是普通作业,而不是主管作业(,这些作业将成为作用域中作业的子级(作用域活动中的MainScope(。

如果《平凡的工作》的任何一个孩子提出了一个例外,它将取消所有的孩子和它自己。CEH不会阻止这种行为。它会得到这些例外情况,并按照指示去做,但它仍然不会阻止取消范围内的Job及其所有子项。最重要的是,它也会在层级上传播异常。TLDR-不会处理崩溃。

为了让你的CEH完成它的工作,你需要将它安装在具有SuperVisorJob(或不可取消的(的上下文中。SupervisorJob假设您正在监督其范围内的异常,因此当引发异常时,它不会取消自身或其子级(但是,如果根本不处理异常,它无论如何都会将其传播到层次结构中(。

例如,在ScopedActivity Scope中:

abstract class ScopedActivity : BaseActivity(), CoroutineScope {
override val coroutineContext = Dispatchers.Main + SupervisorJob() + CoroutineExceptionHandler { _, error -> 
...
}

如果你真的想要,你可以在协同程序层次结构中安装CEH。然而,它看起来很笨拙,不建议使用:

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

然而,如果你想发动一些即发即弃不可抵消的副作用,上述做法可能会很有用:

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

最新更新