我可以从多个片段观察LiveData。我可以用Flow做到这一点吗?如果是,那怎么办?
是。您可以使用emit
和进行此操作collect
。Think 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.getWeatherForecastEveryTwoSeconds().collect {
// Use the weather forecast data
// This will be called 3 times since we have 3
// weather forecast data
}
}
}
我们可以使用map&switchMap从单个LiveData获得多个LiveData。有没有办法从一个源流获得多个流?
流程非常方便。您可以在流内部创建流。假设您要将度数符号附加到每个天气预报数据中。
视图模型
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相同的Fragment中收集数据。这里发生的是视图模型从存储库收集数据,而片段从视图模型收集数据。
使用MutableLiveData,我可以使用变量引用从任何地方更新数据。有什么办法可以对Flow进行同样的操作?
您不能在流程之外释放价值。内部流的代码块仅在有任何收集器时才执行。但是您可以使用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的评论。getWeatherForecast
实际上,不需要在视图模型中为功能创建新的流程。它可以重写为
fun getWeatherForecast(): Flow<String> {
return forecastRepository
.getWeatherForecastEveryTwoSeconds(spendingDetailsRequest)
.map {
it + " °C"
}
}