androidkotlingreenrobot-eventbus

Android EventBus - Sequence for receiving message


I am using EventBus in my application, in which I have one question how it will execute?

I have registered receiver in application, activity and fragment

What I want in app:

Receive message in application class and make some modification and then send it to fragment or activity

Now my question is:

  1. Is eventbus has specific sequence to receive message? like : fragment -> activity -> application
  2. If it has then in which sequence it will execute? a : fragment -> activity -> application b : application -> fragment -> activity c : randomly
  3. And finally how can I receive message in application and then send to fragment or activity by using same messageEvent model class

Solution

  • EventBus do have sequence of delivery but not by default, while subscribing to EventBus you can set the priority using @Subscribe(priority = 0), higher priority subscribers will receive the message first which are on same thread policy. But subscribers are the end point of any transmission meaning modifications done to data in one subscriber won't be sent automatically to another subscriber. To achieve what you need, you can only register primary subscriber as Application, then transform data and broadcast it again with different arguments which the Fragment/Activity will subscribe to.

    class App: Application(){
    
        @Subscribe(threadMode = ThreadMode.MAIN)
        void onOriginalData(OriginalData data){
            //do transformations on data and send transformedData to Activity/Fragment
        }
    }
    
    class Activity: AppCompatActivity {
        
        @Subscribe(threadMode = ThreadMode.MAIN)
        void onTransformedData (TransformedData data){
    
        }
    }