Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android publish/subscribe pattern

Is there a publish/subscribe pattern in android?

What I want to achieve is I have this class that can notify interested party of an event. Then the interested party can do whatever it needs.

Coming from a .net microsoft world, this sort of thing are build in.

Do android have something similar, or I have to write some thing like an observer pattern?

like image 988
pdiddy Avatar asked Dec 02 '11 20:12

pdiddy


3 Answers

Take a look at BroadcastReceiver. I think it's what you're looking for.

like image 146
Ted Hopp Avatar answered Nov 19 '22 19:11

Ted Hopp


I found LocalBroadcastManager the most suitable for in app pub-sub style. You can always use observers but this one makes life more easy:

https://developer.android.com/reference/android/support/v4/content/LocalBroadcastManager.html

EDIT: It seems like there are couple of solutions nowdays. They surely worth mentioning:

  • EventBus as mentioned previously

  • Otto

  • RxBus

like image 24
ApriOri Avatar answered Nov 19 '22 19:11

ApriOri


I think you are speaking in terms of passing events/messages among classes within your application. So this question probably goes down to Java implementation of such a pattern.

There's nothing actually already baked in (i.e. no event system class), one of the most common way to let a class spread an event/message is the Listener technique (see wikipedia, Vogel, IBM).

There are frameworks too, as from this SO answer.

If you are concerned about async messages across thread/processes in Android, then there are Handlers, AsyncTasks and (for inter-process) Parcelables.

like image 4
superjos Avatar answered Nov 19 '22 19:11

superjos