在Flow中的switchIfEmpty等价方法是什么?

huangapple go评论56阅读模式
英文:

switchIfEmpty equivalent in Flow?

问题

我正在将我的应用从RxJava迁移到Flow,并且找不到与switchIfEmpty等效的方法。基本上,如果前一个源没有发出任何内容,我有三个源,我想要依次调用它们。

就像这样:

source1.getData().onEmpty { source2.getData().onEmpty { source3.getData() } }

使用Flow能实现这个吗?

英文:

Im migrating my app from RxJava into Flow and cant find an equivalent for switchIfEmpty. I basically have three sources that i want to consecutively call if the previous one has not emitted anything.

like this:

source1.getData().switchIfEmpty(source2.getData()).switchIfEmpty(source3.getData())

Is this achievable with Flow?

答案1

得分: 1

我认为在默认情况下,没有类似的东西。我们可以很容易地自己创建这样的操作符:

suspend fun main() {
    val f0 = flowOf<Int>()
    val f1 = flowOf(1, 2, 3, 4)
    val f2 = flowOf(5.0, 6.0, 7.0, 8.0)

    f1.ifEmpty(f2).collect { println(it) } // 1, 2, 3, 4
    f0.ifEmpty(f2).collect { println(it) } // 5.0, 6.0, 7.0, 8.0
    f0.ifEmpty(f0).ifEmpty(f1).collect { println(it) } // 1, 2, 3, 4
}

fun <T> Flow<T>.ifEmpty(default: Flow<T>): Flow<T> = onEmpty { emitAll(default) }

我将其命名为ifEmpty,因为switch对于流不太自然。此外,对于集合和序列也有类似的ifEmpty函数。

返回的流使用两个流的最接近的公共超类型。

英文:

I don't think there is anything similar for flows out of the box. We can very easily create such operator by ourselves:

suspend fun main() {
    val f0 = flowOf&lt;Int&gt;()
    val f1 = flowOf(1, 2, 3, 4)
    val f2 = flowOf(5.0, 6.0, 7.0, 8.0)

    f1.ifEmpty(f2).collect { println(it) } // 1, 2, 3, 4
    f0.ifEmpty(f2).collect { println(it) } // 5.0, 6.0, 7.0, 8.0
    f0.ifEmpty(f0).ifEmpty(f1).collect { println(it) } // 1, 2, 3, 4
}

fun &lt;T&gt; Flow&lt;T&gt;.ifEmpty(default: Flow&lt;T&gt;): Flow&lt;T&gt; = onEmpty { emitAll(default) }

I named it ifEmpty, because switch doesn't feel very natural for flows. Also, there are similar ifEmpty functions for collections and sequences.

Returned flow uses the closest common supertype of both flows.

huangapple
  • 本文由 发表于 2023年7月20日 15:15:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76727495.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定