[英]How to trigger Kotlin Flow sequentially and combine the result together?
As title, I got two flows and need to trigger them sequentially first then combine the result.正如标题,我有两个流程,需要先按顺序触发它们,然后合并结果。
data class User(
val name: String,
val age: Int,
)
data class UserStatus(
val status: String,
)
fun flow1() = flow {
delay(300L)
emit(User("Tony Stuck", 50))
}
fun flow2(age: Int) = flow {
val result = when {
age > 60 -> "Over 60"
age < 60 -> "Under 60"
else -> "Equal 60"
}
delay(500L)
emit(UserStatus(result))
}
// The code below isn't what I expected
flow1.flatMapMerge {
flow2(it.age)
}
.collect {
// here I get **UserStatus**, but I want Pair(User, UserStatus)
}
I'v tried using flatMapMerge , but it will map to flow2 finally, what I expect to get is Pair(User, UserStatus), is there any better way to deliver this?我试过使用flatMapMerge ,但它最终会 map 到 flow2,我期望得到的是 Pair(User, UserStatus),有没有更好的方法来实现这个?
You can try the following:您可以尝试以下方法:
flow1.flatMapMerge { user ->
flow2(user.age).map { userStatus ->
user to userStatus
}
}.collect { pair ->
// pair is of type Pair<User, UserStatus>
}
Assuming flow2
is a function and not a variable since it looks like you are passing a parameter, why is flow2
a Flow at all?假设flow2
是一个函数而不是一个变量,因为看起来您正在传递一个参数,为什么flow2
一个 Flow? It only returns one thing.它只返回一件事。 That's better suited for a suspend function or a function that returns a Deferred.这更适合挂起函数或返回 Deferred 的函数。
suspend fun getStatus(age: Int): UserStatus {
val result = when {
age > 60 -> "Over 60"
age < 60 -> "Under 60"
else -> "Equal 60"
}
return UserStatus(result)
}
flow1.map {
it to getStatus(it)
}
.collect {
// this is Pair(User, UserStatus)
}
If you really need flow2
to be a Flow and its first result is the value you need, then:如果你真的需要flow2
成为一个 Flow 并且它的第一个结果是你需要的值,那么:
flow1.map {
it to flow2(it).first()
}
.collect {
// this is Pair(User, UserStatus)
}
What you need is Flow.combine(..)
你需要的是Flow.combine(..)
https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/combine.html https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/combine.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.