John of Ardeal February 2016

Android Event Bus Alternative

Context: In a previous Android application I have developed, I used an event bus (otto by Square) to handle async task results (for example: the result of a server request is posted on the bus and somewhere in the application I intercept that response). Although it did the job, in some article I've read it was mentioned that using such a bus is rather a bad idea as it's considered an antipattern.

Why is that so? What are some alternatives to using an event bus when dealing with results of async operations? I know that, most of the time, there is no standard way to handle things, but is there "a more canonical" method?

Answers


mjosh February 2016

Use RxJava and Retrofit for asynchronous network calls. RxJava provide out of the box support for Retrofit.

Return Observable from retrofit interface.

@GET("/posts/{id}")
public Observable<Post> getData(@Path("id") int postId);

Use it in your activity class -

retrofitBuilderClass.getApi()
 .getData()
 .subscribeOn(Schedulers.newThread())
 .observeOn(AndroidSchedulers.mainThread())
 .subscribe(new Observer < List < Data >> () {
  @Override
  public void onCompleted() {

  }

  @Override
  public void onError(Throwable e) {

  }

  @Override
  public void onNext(List < Data > data) {
  // Display data
  }
 });

Post Status

Asked in February 2016
Viewed 3,426 times
Voted 8
Answered 1 times

Search




Leave an answer