英文:
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<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) }
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论