更改 LiveData 的源流

问题描述

我尝试在存储库中使用 Flow 而不是 LiveData。 在视图模型中:

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 在 vi​​ewModel 的生命周期中始终相同,则它可以正常工作,例如 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
    }
}