我尝试在存储库中使用 Flow 而不是 LiveData。 在 View 模型中:
val state: LiveData<StateModel> = stateRepo
.getStateFlow("euro")
.catch {}
.asLiveData()
存储库:
override fun getStateFlow(currencyCode: String): Flow<StateModel> {
return serieDao.getStateFlow(currencyCode).map {with(stateMapper) { it.fromEntityToDomain() } }
}
如果 currCode 在 viewModel 的生命周期内始终相同,则效果很好,例如 euro
但是如果 currCode 更改为 dollar
该怎么办?
如何使state
显示另一个参数的Flow
?
最佳答案
您需要switchMap
您的存储库调用。
我想你可以做这样的事情:
class SomeViewModel : ViewModel() {
private val currencyFlow = MutableStateFlow("euro");
val state = currencyFlow.switchMap { currentCurrency ->
// In case they return different types
when (currentCurrency) {
// Assuming all of these database calls return a Flow
"euro" -> someDao.euroCall()
"dollar" -> someDao.dollarCall()
else -> someDao.elseCall()
}
// OR in your case just call
serieDao.getStateFlow(currencyCode).map {
with(stateMapper) { it.fromEntityToDomain() }
}
}
.asLiveData(Dispatchers.IO); //Runs on IO coroutines
fun setCurrency(newCurrency: String) {
// Whenever the currency changes, then the state will emit
// a new value and call the database with the new operation
// based on the neww currency you have selected
currencyFlow.value = newCurrency
}
}
关于kotlin - 更改 LiveData 的源流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65467364/