Search code examples
androidandroid-livedatamutablelivedata

why we use val for LiveData in getter instead of var


I saw this code on google and I have a question about it. in this sample they use val for viewState and use getter so if I use val I can change any thing in LiveData so using mutable live data which is created for changing items into it , but during app is not working bcs after postValue I cannot again use the getter bcs it is val....

what I mean :

1) get viewState (OK)

2) _viewState.postvalue() (OK)

3) getviewState with changes (NOT OK BCS ITS VAL AND DOESN;T ACCEPT CHANGES)

so is it not bad that they use val???

  class MainViewModel : ViewModel() {

    private var _viewState: MutableLiveData<MainViewState> = MutableLiveData()
    val viewState: LiveData<MainViewState>
        get() = _viewState

}


Solution

  • viewState Should be val and you no need getViewState to update the view again if already observe the viewState.

    So if you need update the viewState just update _viewState

    Example:

    viewModel

     private var _viewState: MutableLiveData<MainViewState> = MutableLiveData()
        val viewState: LiveData<MainViewState>
            get() = _viewState
    
    fun updateViewState(state:MainViewState){
       _viewState.value = state
    }
    

    on your Activity OnCreate or if you on Fragment OnCreateView you just need Observe the viewState

    viewModel.viewState.observe(this,Observer{viewState->
       // Do your UI things
    }