[英]Kotlin Flow vs Android LiveData
我有一些关于Kotlin Flow的问题
LiveData
。 我可以用Flow
做到这一点吗? 如果是那么如何?map
和LiveData
从单个LiveData
获得多个switchMap
。 有什么办法可以从一个源Flow
获得多个Flow
吗?MutableLiveData
我可以使用变量引用从任何地方更新数据。 有什么办法可以对Flow
做同样的事情吗? 我有一个这样的用例:我将使用callbackFlow{...}
观察SharedPreferences
,这将给我一个单一的源流。 从该流中,我想为每个键值对创建多个流。
这些问题听起来可能很愚蠢。 我是 Rx 和 Flow 世界的新手。
我可以从多个片段中观察 LiveData。 我可以用 Flow 做到这一点吗? 如果是,那怎么办?
是的。 您可以使用emit
和collect
来做到这一点。 认为emit
类似于实时数据postValue
,而collect
类似于observe
。 让我们举个例子。
存储库
// I just faked the weather forecast
val weatherForecast = listOf("10", "12", "9")
// This function returns flow of forecast data
// Whenever the data is fetched, it is emitted so that
// collector can collect (if there is any)
fun getWeatherForecastEveryTwoSeconds(): Flow<String> = flow {
for (i in weatherForecast) {
delay(2000)
emit(i)
}
}
视图模型
fun getWeatherForecast(): Flow<String> {
return forecastRepository.getWeatherForecastEveryTwoSeconds()
}
分段
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
// Collect is suspend function. So you have to call it from a
// coroutine scope. You can create a new coroutine or just use
// lifecycleScope
// https://developer.android.com/topic/libraries/architecture/coroutines
lifecycleScope.launch {
viewModel.getWeatherForecast().collect {
// Use the weather forecast data
// This will be called 3 times since we have 3
// weather forecast data
}
}
}
我们可以使用 map&switchMap 从单个 LiveData 中获取多个 LiveData。 有没有办法从单个源流中获得多个流?
流量非常好用。 您可以在流中创建流。 假设您要对每个天气预报数据使用 append 度数符号。
视图模型
fun getWeatherForecast(): Flow<String> {
return flow {
forecastRepository
.getWeatherForecastEveryTwoSeconds(spendingDetailsRequest)
.map {
it + " °C"
}
.collect {
// This will send "10 °C", "12 °C" and "9 °C" respectively
emit(it)
}
}
}
然后收集与#1相同的片段中的数据。 这里发生的是视图 model 正在从存储库中收集数据,片段正在从视图 model 中收集数据。
使用 MutableLiveData 我可以使用变量引用从任何地方更新数据。 有没有办法对 Flow 做同样的事情?
你不能在流量之外发出价值。 flow里面的代码块只有在有collector的时候才会执行。 但是您可以使用 LiveData 中的 asLiveData 扩展将流转换为实时数据。
视图模型
fun getWeatherForecast(): LiveData<String> {
return forecastRepository
.getWeatherForecastEveryTwoSeconds()
.asLiveData() // Convert flow to live data
}
在你的情况下,你可以这样做
private fun getSharedPrefFlow() = callbackFlow {
val sharedPref = context?.getSharedPreferences("SHARED_PREF_NAME", MODE_PRIVATE)
sharedPref?.all?.forEach {
offer(it)
}
}
getSharedPrefFlow().collect {
val key = it.key
val value = it.value
}
编辑
感谢@mark 的评论。 在视图 model 中为getWeatherForecast
function 创建一个新流实际上是不必要的。 它可以重写为
fun getWeatherForecast(): Flow<String> {
return forecastRepository
.getWeatherForecastEveryTwoSeconds(spendingDetailsRequest)
.map {
it + " °C"
}
}
在新的androidx.lifecycle
ktx 包中有一个新的Flow.asLiveData()
扩展 function。 您可以在我的文章中了解更多信息: https://www.netguru.com/codestories/android-coroutines-%EF%B8%8Fin-2020
在 3 层架构中:数据域表示,流应该发生在数据层(数据库、网络、缓存......),然后正如Samuel Urbanowicz提到的,您可以将 map 流到 LiveData。
一般来说,Flow 几乎就是 RxJava 的 Observable(或 Flowable)。 不要将它与 LiveData 混淆。
更多信息: https://medium.com/@elizarov/cold-flows-hot-channels-d74769805f9
只是想在这里补充 Fatih 的回答,因为已经有一段时间了。
我可以从多个片段观察 LiveData。 我可以用 Flow 做到这一点吗? 如果是那么如何?
是的。 但是您应该这样做的方式有所改变。 您应该使用repeatOnLifecycle
来更安全地从 Flows 发布到 UI。 它是新的,文档很少,但这就是它的样子:
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.getWeatherForecast().collect {
// Safely update the UI
}
}
}
这可确保天气预报仅在显示时更新 UI,而不会浪费资源。 是的,您可以同时对来自同一流的多个片段执行此操作。
我们可以使用 map 和 switchMap 从单个 LiveData 中获得多个 LiveData。 有什么办法可以从一个源流中获得多个流?
这是一个明显的肯定。 流有大量的运算符,如 map 和 switchMap
使用 MutableLiveData 我可以使用变量引用从任何地方更新数据。 有什么办法可以对 Flow 做同样的事情吗?
是的。 我们现在有了MutableStateFlow ,它非常接近并且比MutableLiveData
更强大。
val textFlow = MutableStateFlow("Hello")
someButton.onPress {
textFlow.value = "World"
}
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
textFlow.collect {
someTextView.text = it
}
}
}
上面的 SharedPreferences 代码可以稍微修改一下:
private fun getSharedPrefFlow() = callbackFlow {
val sharedPref = context.getSharedPreferences("SHARED_PREF_NAME", MODE_PRIVATE)
sharedPref?.all?.forEach {
trySend(it) // offer is deprecated
}
}
init {
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
getSharedPrefFlow()
.filter { it.key == BIRTHDAY_KEY }
.collect {
birthdayTextView.text = it.value
}
}
}
}
对于您的用例 - 您可以这样做:
''' yourFlow.filter(...) - 检查键 value.onEach(...) - 做你的神奇 logic.launchIn(viewModelScope) - 或任何地方 ''' 对不起,糟糕的格式,我从电话。
希望这可以帮助。 干杯!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.