Skip to content

1. BaseViewModel

Gabriel Brasileiro edited this page Jun 13, 2020 · 7 revisions

BaseViewModel manages and make interactions with Reducer and SingleLiveData*. In your base we have the implementation of two contracts (EventView<Event> and StateView<State>) to can use with auxiliar extensions onEvent and onStateChanged.

The implementation of BaseViewModel need receive a SingleLiveData<Event>(With event interface) and Reducer<State, StateEvent>(With State and StateEvent interfaces) to works correctly.

When all is fine you can update your State using the updateTo(StateEvent) method passing your respective StateEvent implementation and your view will receive the new state you put in your reducer.

To send events all you need is call the method sendEvent(Event) passing your respective event.

Base implementation checklist:

  • Extend your event implementation from the Event interface;
  • Extend your state data class from the State interface;
  • Extend your state event implementation from the StateEvent interface.

See ReducerScope, State, Event and StateEvent doc to understand better.

Example:

class MainViewModel(
    defaultScreenMessage: String,
    event: SingleLiveEvent<MainEvent>,
    reducer: Reducer<MainData, MainStateEvent>
    // private val anyUseCase: AnyUseCase
) : BaseViewModel<MainData, MainEvent, MainStateEvent>(event, reducer) {

    init {
        updateTo(MainStateEvent.SelectScreenName(defaultScreenMessage))
    }

    fun setScreenMessage(message: String) {
        updateTo(MainStateEvent.SelectScreenName(message))
    }

    fun showPersonScreen() {
        sendEvent(MainEvent.ShowPersonScreen)
    }

    fun showLoadScreen() {
        sendEvent(MainEvent.ShowLoadScreen)
    }
}

Sample Code

Read about listener extensions to process LiveData of your view models with simple way.

Clone this wiki locally