链式Kotlin流量取决于结果状态

问题描述

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

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

最明显的方法是:

Dictionary<string,string> parameters = new Dictionary<string,string>();
        Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
        Encoding.GetEncoding("windows-1252");
        LocalReport report = new LocalReport("report1.rdlc");
        var result = report.Execute(GetRenderType("pdf"),1,parameters);
        return result.MainStream;

但是它看起来像是众所周知的“回调地狱”。您有任何避免的想法吗?

解决方法

我相信可以用Method __getattr__将其弄平:

class Character:
    # more things...
    def attack(self,other):
        remaining = 0
        h = 0

        # Dice Mechanism - Based of AdB + C#    
        while remaining < self.get_attack_a():
            add = random.randint(1,self.get_attack_b())
            h += add
            remaining += 1
        print(h)
        # more things...
,

我认为,在这种使用情况下,您可能应该使用suspend函数,并使用await() compose。 错误应通过here中所述的异常传递。

,

对МихаилНафталь提供的解决方案进行了一些修改

    methodA()
        .flatMapMerge {
            when (it) {
                is Result.Success -> methodB(it)
                is Result.Failure -> emptyFlow()
            }
        }.flatMapMerge {
            when (it) {
                is Result.Success -> methodC(it)
                is Result.Failure -> emptyFlow()
            }
        }.collect {
            when (it) {
                is Result.Success -> TODO()
                is Result.Failure -> TODO()
            }
        }

将一个流的输出合并到另一个流是flatMap的目标,因此使用flatMap似乎更干净。

如果此Result类具有mapfoldgetOrNull类型的方法,则可以对其进行更多清理,并可以删除when块。

此外,如果您需要传播故障以进行收集,则可以用仅输出所需故障的流来替换对emptyFlow的调用。