1

Is it good practice to use Otto event bus bi-directionally?

I mean, send events from controller to view, and view to controller?

Or is it just meant to publish results meaning its purpose is only events from controller to view?

Thanks

oxygenpt
  • 368
  • 2
  • 17

1 Answers1

4

Good question. Here is my thoughts on this. I use Otto for a while and use it bi-directionally. From my experience there is nothing against doing this. I have just defined couple of rules helping me keep everything under control.

One-to-many pattern must be confirmed. I mean here, that one producer should normally notify multiple subscribers. Of course, at different point in time there can be zero or more subscribers. But if you have a case, where by-design maximum number of subscribers is just one, then you trying to dispatch rather a "command", than an "event". For such cases I would use a direct call instead of posting a event.

Another thing to avoid should be a situation, when one event triggers another event, which, in turn, triggers first event again. You can run in infinite event chain here. This might happen when same class has the both subscriber and producer methods. If I have such classes, I try to keep those methods as independent as possible.

And of course I always use Android components' lifecycle to register and unregister publishers and subscribers dynamically. I start with onResume() and onPause() methods and, if needed, I'm going up to onStart() or even onCreate().

sergej shafarenka
  • 20,071
  • 7
  • 67
  • 86
  • When you mention one-to-many here - you do NOT mean that there need to be many subscribers *simultaneously*, do you? An EventBus is routinely used for bi-directional communication between Activities and a `Service` for example; where the Service doesn't care who is subscribed (or even whether there are any subscribers). Often at most ONE `Activity` is subscribed to it. A typical use case for this is where the `Service` is used for making network calls. A direct call could be used here but it makes much more sense to use an Event Bus pattern (implemented using an actual Event Bus or Broadcasts) – curioustechizen Oct 14 '14 at 07:40
  • @curioustechizen You are right. That was bad wording from me. I have just fixed the answer. – sergej shafarenka Oct 14 '14 at 08:39