Max Rockwood Max Rockwood - 1 month ago 10
Java Question

EventBus, is it possible to get the sticky event in the onCreate?

I am sending data from lets say

SplashActivity
to main activity using EventBus's
postSticky
method, and depending on that data am creating tabs in
MainActivity
using
ViewPager
.

So far it works great and I can setup
ViewPager
in
@Subscribe onEvent(Example data)
method.

For Example:

@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void onEvent(Example event){
mainContentList = event.mainContentList;

if (mViewPager != null) {
setupViewPager(mViewPager, mainContentList);
}

TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}


The issue is arises when we call
MainActivity
from
ActivityC
,


Now the
@Subscribe onEvent(Example data)
would not be called because we are posting to it from
SplashActivity
only, so it won't be called and the
ViewPager
doesn't gets updated.


What I want:


I want to get the data from StickyPost as early as possible so I can initialize the
ViewPager
in the
OnCreate
method of the activity.


I know I can use Application level Singleton or create a
DataHolder
class etc to store the data but is there anyway to achieve this using
EventBus
?

Thanks for your time an if you need any more info let me know and I will update.

Answer

The Solution to problem was pretty simple, we can simple. we call getStickyEvent anywhere, something like this

Example:

EventBus eventbus = Bus.getInstance();

ExampleEvent event = eventbus.getStickyEvent(ExampleEvent.class);

    if ( event != null ){

        // Whatever we want to do with event

        // and then we can remove stickyEvent if we don't need it anymore

        eventbus.removeStickyEvent(event);
    }
Comments