gpt4 book ai didi

kotlin - 当您的所有协程已经用 CouroutineExceptionHandler 包装时,如何发现 "Job was cancelled"异常的来源?

转载 作者:行者123 更新时间:2023-12-02 12:26:50 26 4
gpt4 key购买 nike

我阅读了所有 kotlinx UI docs并实现一个像那里描述的 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 */ }
}

希望能帮助到你

关于kotlin - 当您的所有协程已经用 CouroutineExceptionHandler 包装时,如何发现 "Job was cancelled"异常的来源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58734114/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com