事件总线片段注销 [英] Event Bus Fragment Unregister

查看:233
本文介绍了事件总线片段注销的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经注册到事件总线一个启动画面片段:

I've a splashscreen Fragment that is registered to event bus:

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

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

如果屏幕会自动锁定(或者可以调用的onStop任何其他事件),容器的活动去的onStop和碎片没有更多的能够接收(网络)事件。我在想的移动注销的逻辑以的onDestroy 方式。这是个好主意吗?

If the screen goes autolock (or any other event that could call onStop), the container activity goes onStop and the fragment is no more capable to receive the (network) event. I'm thinking about moving "unregister" logic to onDestroy method. Is it a good idea?

推荐答案

您的可以的移动事件总线事件在onStart()的onStop(),但你应该知道,某些方法不能被称为后的onSaveInstanceState()(例如,解雇DialogFragment你崩溃了)。

You can move the event bus events to onStart() and onStop(), BUT you should know that certain methods cannot be called after onSaveInstanceState() (for example, dismissing a DialogFragment crashes you out).

所以,尽管这个例子是奥托,我把它切换到EventBus,和我个人,而应用程序被暂停存储事件的包装。

So while this example was for Otto, I switched it to EventBus, and I personally have a wrapper 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();
            }
        }
    }
}

然后在各种各样的BaseActivity,

Then in a BaseActivity of sorts,

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();
     }
}

这篇关于事件总线片段注销的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆