Fragment of autorun events Unregister

I have a splash screen fragment registered for the event bus:

@Override public void onStart() { super.onStart(); EventBus.getDefault().register(this); } @Override public void onStop() { EventBus.getDefault().unregister(this); super.onStop(); } 

If autoplay appears on the screen (or any other event that may cause onStop), the activity of the container goes to Stop, and the fragment is no longer able to receive the (network) event. I am thinking of moving the "unregister" onDestroy method . Is that a good idea?

+6
source share
2 answers

You can move bus event events to onStart() and onStop() , BUT you should know that certain methods cannot be called after onSaveInstanceState() (for example, rejecting DialogFragment will result in failure).

So, although this example was for Otto, I switched it to EventBus, and I personally have a shell that stores events while the application is paused.

 public enum SingletonBus { INSTANCE; private static String TAG = SingletonBus.class.getSimpleName(); private final Vector<Object> eventQueueBuffer = new Vector<>(); private boolean paused; public <T> void post(final T event) { if (paused) { eventQueueBuffer.add(event); } else { EventBus.getDefault().post(event); } } public <T> void register(T subscriber) { EventBus.getDefault().register(subscriber); } public <T> void unregister(T subscriber) { EventBus.getDefault().unregister(subscriber); } public boolean isPaused() { return paused; } public void setPaused(boolean paused) { this.paused = paused; if (!paused) { Iterator<Object> eventIterator = eventQueueBuffer.iterator(); while (eventIterator.hasNext()) { Object event = eventIterator.next(); post(event); eventIterator.remove(); } } } } 

Then in the BaseActivity class,

 public class BaseActivity extends AppCompatActivity { @Override public void onPostResume() { super.onPostResume(); SingletonBus.INSTANCE.setPaused(false); } @Override public void onPause() { SingletonBus.INSTANCE.setPaused(true); super.onPause(); } } 
+10
source

I recently had a similar problem. First I used Otto, and then switched to greenrobot EventBus. With EventBus you can register your objects sluggishly. EventBus.getDefault().registerSticky(this) That is, this object will automatically receive every sticky event that it expects after registration. Then these events should be posted sticky. ( EventBus.getDefault().postSticky(event) )

Consider removing sticky events if you no longer need them ( EventBus.getDefault().removeSticky(Event.class) ). Therefore, if you want to receive this event only after its removal. Perhaps this approach may suit your needs.

+2
source

All Articles