Kotlin流,回调 [英] Kotlin Flow, callback

查看:122
本文介绍了Kotlin流,回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了以下扩展函数:

fun <T> Flow<T>.handleErrors(showError: Boolean = false, retry: Boolean = false, 
                             navigateBack: Boolean = true): Flow<T> =
    catch { throwable ->

        var message: String? = null

        if (showError) {
            when (throwable) {

                is HttpException -> {
                  postEvent(EventType(retry))
                }
             }
          }

扩展函数然后将可抛出的类型发布到基本活动,并根据发布的事件类型显示相关的对话框。

如果该事件是重试,我希望重试失败的流程。

例如,如果HTTP异常为400,并且在对话框上选择重试时,我想重试失败的呼叫。

是否可以将回调添加到已失败且可以从其他活动或片段调用的Kotlin流?

推荐答案

我认为您不想在单独的块中重试,您可以这样组织您的代码


fun presentDialog(onClick: (Boolean) -> Unit) {
    // some code to compile you dialog / install callbacks / show it
    onClick(true) // user-click-retry
}

suspend fun main() {
    val source = flow {
        while (true) {
            emit(
                if (Math.random() > 0.5) Result.success(100) else Result.failure(IllegalArgumentException("woo"))
            )
        }
    }

    source.collect { result ->
        suspendCancellableCoroutine<Unit> { cont ->
            result.onSuccess {
                println("we are done")
            }.onFailure {
                presentDialog { choice ->
                    if (choice) {
                        cont.resumeWith(Result.success(Unit))
                    } else {
                        println("we are done")
                    }
                }
            }
        }
    }
}

现在有一些解释

如您所知,Flow是cold,如果您不收集它,它将永远不会生成,因此,如果您的Collect块不返回,emit之后的构建器中剩余的thunk将不会被执行, 通过调用collect块中的suspendCoroutine暂停flowBuilder的执行,如果出现HTTP错误,则显示您的对话框,并根据用户响应恢复执行,如果没有错误或用户没有单击重试,则不做任何事情。上面的示例代码在某种程度上具有误导性,对于一般情况,您不会在一切正常时提供重试机制,因此while true块可能会更改为


flow {
   do {
     val response = response()
     emit(response)
   } while(response.isFailure)
}.collect {
   it.onSuccess {  println("of-coz-we-are-done") }.onFailure {
     // suspend execution and show dialog
     // resume execution when user click retry
   } 
}

这可能会让您感到欣慰,因为流已经结束了,但实际上它基本上是相同的

这篇关于Kotlin流,回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆