Change source Flow for LiveData

Viewed 515

I try to to use Flow instead of LiveData in repos. 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?

How to make state to show a Flow for another param?

1 Answers

You need to switchMap your repository call.

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