【发布时间】:2021-10-31 14:49:23
【问题描述】:
我正在嵌套启动的流中从数据存储区收集数据{}。
viewLifecycleOwner.lifecycleScope.launchWhenStarted {
launch {
DataStore.userName.collect {
// it emits string value
Log.e(TAG, it )
}
}
launch {
DataStore.userPhone.collect {
// it emits string value
Log.e(TAG, it )
}
}
launch {
DataStore.userAddress.collect {
// it emits string value
Log.e(TAG, it )
}
}
}
有没有更好的方法来收集片段中的流?就像在单个启动块中收集所有数据一样。
【问题讨论】:
-
使用可以使用 combine :
fun <T1, T2, T3, R> combine(flow: Flow<T1>, flow2: Flow<T2>, flow3: Flow<T3>, transform: suspend (T1, T2, T3) -> R): Flow<R>。所以在这里使用combine(DataStore.userName, DataStore.userPhone, DataStore.userAddress, ::Triple).onEach{ (name, phone, address) -> .... }.launchIn(scope)- 考虑在DataStore中添加这个作为一种方便的方法。
标签: android kotlin kotlin-coroutines kotlin-flow