gpt4 book ai didi

kotlin - 链 kotlin 流取决于结果状态

转载 作者:行者123 更新时间:2023-12-04 08:46:16 24 4
gpt4 key购买 nike

我正在寻找最“干净”的方式来实现以下逻辑:

  • 我有N个方法,每个人都返回Flow >(类型不同)
  • 我想链接这些方法,所以如果 1 返回 Result.Success,则调用 2nd,依此类推。

  • 最明显的方法是:
    methodA().map { methodAResult ->
    when (methodAResult) {
    is Result.Success -> {
    methodB(methodAResult).map { methodBResult ->
    when (methodBResult) {
    is Result.Success -> {
    methodC(methodAResult).map { methodCResult ->
    when (methodCResult) {
    is Result.Success -> TODO()
    is Result.Failure -> TODO()
    }
    }
    }
    is Result.Failure -> TODO()
    }
    }
    }
    is Result.Failure -> TODO()
    }
    }
    但它看起来像一个众所周知的“回调 hell ”。你有什么想法如何避免它吗?

    最佳答案

    我相信这可以用 transform operator 来扁平化。 :

    methodA().transform { methodAResult ->
    when (methodAResult) {
    is Success -> methodB(methodAResult).collect { emit(it) }
    is Failure -> TODO()
    }
    }.transform { methodBResult ->
    when (methodBResult) {
    is Success -> methodC(methodBResult).collect { emit(it) }
    is Failure -> TODO()
    }
    }.transform { methodCResult ->
    when (methodCResult) {
    is Success -> TODO()
    is Failure -> TODO()
    }
    }

    关于kotlin - 链 kotlin 流取决于结果状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64303904/

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