简体   繁体   English

更改 LiveData 的源流

[英]Change source Flow for LiveData

I try to to use Flow instead of LiveData in repos.我尝试在 repos 中使用 Flow 而不是 LiveData。 In viewModel:在视图模型中:

val state: LiveData<StateModel> = stateRepo
.getStateFlow("euro")
.catch {}
.asLiveData()

Repository:存储库:

 override fun getStateFlow(currencyCode: String): Flow<StateModel> {
    return serieDao.getStateFlow(currencyCode).map {with(stateMapper) { it.fromEntityToDomain() } }
 }

It works fine if currCode if always the same during viewModel's lifetime, for example euro but what to do if currCode is changed to dollar ?如果 currCode 在 viewModel 的生命周期中始终相同,则它可以正常工作,例如euro ,但如果 currCode 更改为dollar怎么办?

How to make state to show a Flow for another param?如何使state显示另一个参数的Flow

You need to switchMap your repository call.您需要switchMap您的存储库调用。

I imagine you could dosomething like this:我想你可以这样做:

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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM