Question

According to Android developer pages, fragments communicate through its host activity. This tends to produce rigid fragment <-> host relationships and verbose implementations of even the simplest event propagations - it gets worse if you have multiple recipients, etc.

I'd like to propose an alternative approach, which has worked for me. Please let me know if you see a problem with it, particularly regarding memory leaks, as I have actors registering with a singleton.

In summary, I have an EventHub singleton which fragments post their events to, not caring if there is anybody listening "on the other side". My fragments (or activity) are registering with the EventHub passing its Handler instances:

Activity/fragment listening for events from other fragments:

public void onResume()
{
    super.onResume();

    // Register self with the hub and start receiving events
    EventHub.getInstance().register( handler_ );
    ...
}

/** Don't leak handlers. */
@Override
public void onPause() {
    // Remove self from the event hub.
    EventHub.getInstance().unregister( handler_ );
}

/** Dispatch events. */
private Handler handler_ = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch( msg.what ) {
            ....
        }
    }
};

Fragment emitting events:

    button.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v) {
                EventHub.getInstance().post( Message m );
            }
        });
Was it helpful?

Solution

Instead of developing your own method, I suggest you look at Functional Reactive Programming. Observables and friends were created exactly for the issue you describe. Also, you won't have to think too much about memory leaks as long as you play along the rules.

Here is a tutorial for starters: http://mttkay.github.io/blog/2013/08/25/functional-reactive-programming-on-android-with-rxjava/ But Google has even more to say about it: https://www.google.hu/search?q=android+rxjava

This is not a magic solution, and it's quite complex at first look but if you grasp the idea, then it will help make your software simpler and a lot safer.

Otherwise I don't see many issues with your proposed solution but it will be hard to keep the registrations consistent.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top