Search code examples
androidretrofitevent-busgreenrobot-eventbus

How to pair retrofit with event bus


Im trying to pass data between fragments and retrofit services with usage of event bus.

Some conditions which can make things a bit complicated:

  1. Fragment1 and Fragment2 can request identical data so only one request to server should be executed.
  2. Fragment1 and Fragment2 can receive same data type with different data in it(e.g. Fragment1 shows user data,Fragment2 shows user friend's data).That makes event bus trigger both onUserResponse(User user) in Fragment1 and onUserFriendResponse(User userFriend) in Fragment2

My current approach is responce wrapping. Do you know any better ways to do it?


Solution

  • Without any more information, it's hard to know enough to answer in detail.

    1. You can cache request data if you are confident it will not change often. The API service class (which makes your Retrofit calls) can decide whether to make a HTTP request, or just serve the cached data. This cache should be cleared if there is a chance the data has changed, e.g. when logging in / out, or performing some request which will change the data.

    2. For most event bus systems (like Otto for example) it doesn't matter what the bus response method is called, but rather depends on the parameter object class, which in your case is User. It would be fairly typical to wrap the data in an event object (as you say you are doing), so you could have onUserResponse(UserResponseEvent event) in Fragment1 and onUserFriendResponse(UserFriendResponseEvent event) in Fragment2. Each event object simply wraps User.

    E.g.

    public class UserResponseEvent {
        private final User user;
    
        public UserResponseEvent(User user) {
            this.user = user;
        }
    
        public User getUser() {
            return user;
        }
    }