Is that possible that when I click the button and then after waiting some time (~5sec) rotate the screen the post may be missed, because the activity didn't manage to re-register in time? I believe that I've managed to produce that. But it was like 1 from 50 tries:)
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends BaseActivity {
@BindView(R.id.post)
Button mPost;
@BindView(R.id.result)
TextView mResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
@Override
protected void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
@Override
protected void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
@OnClick(R.id.post)
void onPostClick() {
HandlerThread handlerThread = new HandlerThread("MyThread");
handlerThread.start();
Handler handler = new Handler(handlerThread.getLooper());
handler.post(new Runnable() {
@Override
public void run() {
Log.e(TAG, Thread.currentThread().getName());
try {
Thread.sleep(5000);
EventBus.getDefault().post(new MyObject("wow"));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onResult(MyObject object) {
Log.e(TAG, "POST " + object);
}
static class MyObject {
String val;
public MyObject(String val) {
this.val = val;
}
@Override
public String toString() {
return val;
}
}
}
There's a chance Activity code miss the event due to recreation, however if this is a problem then you most likely should be posting your events as sticky
:
Some events carry information that is of interest after the event is posted. For example, an event signals that some initialization is complete. Or if you have some sensor or location data and you want to hold on the most recent values. Instead of implementing your own caching, you can use sticky events. EventBus keeps the last sticky event of a certain type in memory. The sticky event can be delivered to subscribers or queried explicitly. Thus, you don’t need any special logic to consider already available data.
http://greenrobot.org/eventbus/documentation/configuration/sticky-events/
Also, some suggests moving registration handling from onStart
/onStop
to onCreate
/onDestroy
. I think is is bad idea - you usually do not care the events if you are in background, therefore I'd also recommend moving reg/unreg code to onResume
/onPause
instead.