Jalpesh
Jalpesh

Reputation: 1134

Android :Green robot eventbus : Multiple events received on single post

I am using Green robot event bus in Android

I am calling all events using EventBus.getDefault().post and onStop I am calling EventBus.getDefault().unregister(this); in my Activity. However once I press back and reopen the application, on a single event post, multiple onEvent()'s are received. Has anyone else faced this issue?

@Override
protected void onStart() {
    super.onStart();
    getBus().register(this);
}

@Override
protected void onPause() {
    getBus().unregister(this);
    super.onPause();
}

@Override
protected void onStop() {
    getBus().unregister(this);
    super.onStop();
}


protected EventBus getBus() {
    return EventBus.getDefault();
}

Upvotes: 4

Views: 1914

Answers (1)

Jalpesh
Jalpesh

Reputation: 1134

I figured out the problem. Each time the app returned from the background, the register function was called again. As opposed to my wrong assumption, green robot did not manage duplicates and I needed to add a check before registering it. So here is how my final code looks like.

mBus = EventBus.getDefault();

void registerAndCheck(Object helper)
{
    if(!mBus.isRegistered(helper))
    {
        mBus.register(helper);
    }
}


mFileHelper = new FilesHelper();
registerAndCheck(mFileHelper);

Hope it helps someone.

Upvotes: 6

Related Questions