将两个状态流组合成一个流
我目前正在尝试将两个流组合在一起,并使用该结果将其显示为Android中的构图视图。我当前这样的初始化:
private var flowA: MutableStateFlow<String?> = MutableStateFlow(null)
private var flowB: MutableStateFlow<String?> = MutableStateFlow(null)
var combinedFlows: Flow<Pair<String?, String?>> =
flowA.combine(flowB) {a, b ->
Pair(a, b)
}
像这样发射:
// Some logic to create string
flowA.emit("New String")
// More logic to create another string
flowB.emit("Another New String")
在撰写视图中,我正在收集这样的收集:
var pairStrings = viewModel.pairStrings.collectAsState()
当我从flowa
和flowb
发出时,组合流从未发出任何数据 。 。我在这里缺少什么吗?
-edit-
这是在视图模型中:
val pairStrings: StateFlow<Pair<String?, String?>> = combinedFlows
.stateIn(
scope = viewModelScope,
initialValue = Pair(null,null),
started = SharingStarted.Eagerly,
)
I am currently trying to combine two streams and use that result to display into a Compose view in Android. I currently initialize it like this:
private var flowA: MutableStateFlow<String?> = MutableStateFlow(null)
private var flowB: MutableStateFlow<String?> = MutableStateFlow(null)
var combinedFlows: Flow<Pair<String?, String?>> =
flowA.combine(flowB) {a, b ->
Pair(a, b)
}
Emit like so:
// Some logic to create string
flowA.emit("New String")
// More logic to create another string
flowB.emit("Another New String")
In the compose view I am collecting like this:
var pairStrings = viewModel.pairStrings.collectAsState()
The combined stream is never emiting any data when I emit from flowA
and flowB
. Is there something I am missing here?
--Edit--
This is in the view model:
val pairStrings: StateFlow<Pair<String?, String?>> = combinedFlows
.stateIn(
scope = viewModelScope,
initialValue = Pair(null,null),
started = SharingStarted.Eagerly,
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您没有提供太多信息,但是您需要运行/订阅组合流程。我认为您需要执行以下操作:
sharein
操作员在单独的coroutine中运行上游流程。这样做,您将能够消耗流量。您需要传递
coroutinescope
,假设您在ViewModel中进行此调用(应该是最好的地方),则可以使用view> viewModelsCope
。您还需要传递sharingState
,该>将确定在启动和停止共享时控制的策略。在这种情况下,我正在使用whilesubscribed
,它在最后一个订户消失时立即停止流动。You didn't provide much information, but you need to run/subscribe to the combined flow. I think you need to do the following:
The
shareIn
operator runs the upstream flow in a separate coroutine. Doing this, you'll be able to consume the flow.You need to pass a
CoroutineScope
, assuming you're doing this call in a ViewModel (which should be the best place), you can use theviewModelScope
. You also need to pass theSharingState
which will determine the strategy that controls when sharing is started and stopped. In this case, I'm usingWhileSubscribed
which immediately stops the flow when the last subscriber disappears.