eansn
eansn

Reputation: 91

Observer pattern vs Event Bus message approach

I've been looking at MVC implementations and Event-bus closely.

Why not use Event-bus instead of Observer Pattern to implement a MVC application?

For example, lets say I have two classes Model and View, In typical observer pattern it would be:

public class Model implements Subject { ... }

public class View implements Observer { ... }

Instead, what is the benefit/drawback of an approach using green robot event bus or any other Event-bus?

It would be something like:

public class Model {
   private int field = 0; 

   void someFunctionNowTriggerStateChange() {
     this.field = field + 1;
     ...EventBus.getDefault().post(this); //pass itself as the event
   }
}

public class View {

  @Subscribe onModelUpdated(Model model) {
    updateTextLabel(model);
    //other model updates
  }   
}

What are the issues (if any) of using the EventBus to implement MVC vs typical Observer?

Upvotes: 5

Views: 3296

Answers (1)

Ori Marko
Ori Marko

Reputation: 58812

EventBus implements publisher subscriber pattern,

EventBus is an open-source library for Android and Java using the publisher/subscriber pattern for loose coupling.

The difference from observer pattern is that publisher is loosely coupled from subscribers

publisher and subscriber don’t know about the existence of one another. There is a third component, called broker or message broker or event bus, which is known by both the publisher and subscriber, which filters all incoming messages and distributes them accordingly. In other words, pub-sub is a pattern used to communicate messages between different system components without these components knowing anything about each other’s identity.

One advantage is that Publisher/Subscriber pattern can be normally/easier to be implemented in an asynchronous way because having a third component, broker, assist to implement asynchronous behavior, because execution becomes loosely coupled

Another advantage, because Publisher/Subscriber pattern is loosely coupled, it will be more intuitive/easier to implement also multiple subscribers

Observer pattern is mostly implemented in a synchronous way, i.e. the Subject calls the appropriate method of all its observers when some event occurs. The Publisher/Subscriber pattern is mostly implemented in an asynchronous way (using message queue).

If you don't need (and won't need) such broker, you are safe to use Observer pattern, which will make your code smaller and simpler

Upvotes: 7

Related Questions