2

我尝试在 repos 中使用 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

4

1 回答 1

2

您需要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
    }
}
于 2020-12-27T15:31:48.973 回答