ViewModel function implementation with MutableLiveData or use directly a LiveData?

39 Views Asked by At

I have a function getAdressSuggestions who return a list of AddressResult

I wonder what is the best implementation between this two :

The first one is with a MutableLiveData we have inside the viewModel this :

private val _adressState = MutableLiveData<AddressSearchUIState>()
val adressState: LiveData<AddressSearchUIState>
    get() = _adressState

The AddressSearchUIState is a sealed class who contains a data class named Success

sealed class AddressSearchUIState {
    data class Success(val suggestions: List<AddressResult>) : AddressSearchUIState()
}

And this is the function inside the viewModel

fun getAdressSuggestions(text: String) =
    viewModelScope.launch(dispatcher) {
        val result = geocodingRepository.predictAddresses(text.lowercase())
        _adressState.postValue(AddressSearchUIState.Success(result))
    }

We get the result from the repository and post the value in the MutableLiveData _adressState

And inside the fragment I create an observer like this

viewModel.adressState.observe(viewLifecycleOwner) { adresses ->
        if (adresses is InformationsViewModel.AddressSearchUIState.Success) {
            //Do things
        }
    }

I can now do it another way with less code and LiveData like this :

fun getAdressSuggestions(text: String) = liveData {
    viewModelScope.launch(dispatcher) {
        emit(geocodingRepository.predictAddresses(text.lowercase()))
    }
}

and observe it in Fragment like this

viewModel.getAdressSuggestions(it).observe(viewLifecycleOwner) { adresses ->
                //Do things
}

For me the second option is lighter and better but am I missing something ?

In which use case the first option will be better to implement ?

0

There are 0 best solutions below