android - Advantages of injecting Otto event bus instead of using static singleton -


in android apps i'm using otto event bus , dagger dependency injection.

in userguide of otto , in many blog posts it's recommended use injection bus singleton. have done time, lately i'm getting more doubtful if injecting bus has advantages on using simple static singleton.

with injection have inject every custom view or viewholder want able post ui events on bus. dagger seems bit clumsy inject every class need bus. sure, pass bus constructor or setter method, can kind of clumsy if think adapter many different view types example.

and don't see advantages in injecting bus. in case of otto concrete implementation injected (an instance of bus) , never change. wrapping otto de-coupling not make sense if think, because of way subscription works.

so, see advantages of injecting otto don't see?

in opinion, should wrap event bus in own class , use dependency injection techniques in order pass clients.

enter image description here

there several advantages approach on obtaining reference through call static getinstance() method:

  • your dependencies become explicit. when obtain references objects through static calls dependencies hidden inside implementation of clients, make code fragile , harder understand.
  • will easier switch different implementation of event bus if such need arises.
  • injected dependencies easier mock in tests
  • the fact dependency injection techniques introduce degree of struggle thing - if you're struggling, indication doing wrong. in case, suspect you're abusing event bus.

i possible you're abusing event bus because don't see why need have reference in view subclasses. i'd guess post notifications user interactions event bus, , subscribe activity or fragment event bus in order intercept these events. event bus wrong tool in case (even though works great).

the reason why event bus wrong tool in case because fragments , activity can have direct access contained view objects. can references these views , register fragments , activities listeners. no need decouple here.

on contrary: think case go , refactor views in such way nothing being posted event bus anymore (say, business requirements changed). since views notifications loosely coupled containing fragment or activity through event bus, probable you'll forget remove events handling logic fragment , activity, leaving "dead code" behind. gets messy quickly.

the better practice use observer design pattern , let views notify activities , fragments directly, , when handling involves component (which can't reached fragment , activity; e.g. fragment or activity) these components post events event bus. if follow approach, need have reference event bus in "top level components" only, , no struggling involved.

p.s. have published blog post introduces best practices dependency injection in android.


Comments