0

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

}

Jakir Hossain
  • 3,830
  • 1
  • 15
  • 29
Mohamad Alemi
  • 13
  • 1
  • 7

1 Answers1

1

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
}
MOF
  • 163
  • 1
  • 10
  • 1
    what is the difference between var viewState and val viewState in this code? and if I use val viewState why It can be updated ? I mean it is val not var and shouldn't be updated – Mohamad Alemi Dec 05 '19 at 10:01
  • It's the exact same thing as `private final MutableLiveData` vs `private MutableLiveData` in Java. Just because the reference is final doesn't mean you can't change a value inside it. – EpicPandaForce Dec 05 '19 at 10:07
  • so you mean get() = _viewState just change the value of LiveData which is permissible in final variables? – Mohamad Alemi Dec 05 '19 at 10:12
  • Wouldn't `_viewState` also be `val` opposed to `var`? – kyhule Dec 16 '22 at 15:51