Otto events received twice

1.2k Views Asked by At

I try to use Otto. I think it works so far but I receive the events twice.

This is what I have (I followed the example on GitHub):

The producer:

public class NetworkChangeReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(final Context context, final Intent intent)
    {
        Log.i("ralphs", "onReceive");

        // .... more stuff

        final Bus bus = TRaumfeldApp.getInstance().getBus();
        bus.register(this);
        bus.post(new NetworkChangeEvent());
        bus.unregister(this);
    }

    @Produce
    public NetworkChangeEvent produceAnswer()
    {
        Log.i("ralphs", "produceAnswer");
        return new NetworkChangeEvent();
    }
}

The Subscriber:

public class MainActivity extends ActionBarActivity
{
    private Bus              mBus;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // otto event bus
        mBus = TRaumfeldApp.getInstance().getBus();
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        mBus.register(this);
    }

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

    @Subscribe
    public void answerAvailable(NetworkChangeEvent event)
    {
        Log.i("ralphs", "answerAvailable");
    }
}

The log locks like this:

I/ralphs﹕ onReceive
I/ralphs﹕ produceAnswer
I/ralphs﹕ answerAvailable
I/ralphs﹕ answerAvailable

Why I receive the events twice?

3

There are 3 best solutions below

0
On BEST ANSWER

When your subscriber registers, it gets the first event from the @Produce-annotated method if an object with such methods is registered. The second event is from the explicit post() operation.

You don't need to register in order to post but you do need it for the @Produce annotation.

0
On

You don't need to register, when you want to post an event.

0
On

As far as I know, this problem is not connected with Otto Events Bus, which works correctly. This bug is connected with Broadcast Receivers in Android API and Network Change Event. It is also device specific problem. Some devices may receive 2 or 3 Network Change Events. You can handle that problem by creating a class called e.g. NetworkState with a static variable indicating current status of your network connection and post event to the bus only in the case, when connectivity status was changed. This problem was handled in NetworkEvents library. You can browse its source code and see how it was handled there or use this library in your project. Especially you can take a look at NetworkConnectionChangeReceiver class. It's not the best solution, but we cannot do anything else until Broadcast Receivers don't work as we expect.