Skip to content

Communicate between ViewModels using Event Dispatcher

Henry Tao edited this page Apr 24, 2016 · 1 revision

Register & Dispatch Event

Event should be unique in application level. Duplicated events may cause RuntimeException DuplicatedEventException.

Noted that: You can dispatch event with up to 9 parameters. Dispatcher can cause Class cast exception at runtime if subscriber's parameters don't match. This is can be prevented with UnitTest. Check out: Event, Event1, Event2, Event 3... in me.henrytao.mvvmlifecycle.event package.

public class TaskItemViewModel extends MVVMViewModel {

  public TaskItemViewModel() {
    register(this, Event.ON_TASK_ITEM_CLICK);
    register(this, Event.ON_ACTIVE_TASK_ITEM_CLICK);
    register(this, Event.ON_COMPLETE_TASK_ITEM_CLICK);
  }

  public void onItemCheckedChanged(boolean isChecked) {
    if (isChecked) {
      dispatch(Event.ON_COMPLETE_TASK_ITEM_CLICK, mTask);
    } else {
      dispatch(Event.ON_ACTIVE_TASK_ITEM_CLICK, mTask);
    }
  }

  public void onItemClick() {
    dispatch(Event.ON_TASK_ITEM_CLICK, mTask);
  }

  public enum Event {
    ON_TASK_ITEM_CLICK,

    ON_ACTIVE_TASK_ITEM_CLICK,
    ON_COMPLETE_TASK_ITEM_CLICK
  }
}

Subscribe to Event

public class TasksViewModel extends MVVMViewModel {

  public TasksViewModel() {
  }

  @Override
  public void onCreate() {
    super.onCreate();

    manageSubscription(subscribe(TaskItemViewModel.Event.ON_TASK_ITEM_CLICK, new Event1<>(this::onTaskItemClick)),
        UnsubscribeLifeCycle.DESTROY);
    manageSubscription(subscribe(TaskItemViewModel.Event.ON_ACTIVE_TASK_ITEM_CLICK, new Event1<>(this::onActiveTaskItemClick)),
        UnsubscribeLifeCycle.DESTROY);
    manageSubscription(subscribe(TaskItemViewModel.Event.ON_COMPLETE_TASK_ITEM_CLICK, new Event1<>(this::onCompleteTaskItemClick)),
        UnsubscribeLifeCycle.DESTROY);
  }

  protected void onActiveTaskItemClick(Task task) {
    ...
  }

  protected void onCompleteTaskItemClick(Task task) {
    ...  
  }

  protected void onTaskItemClick(Task task) {
    ...
  }
}