Advantage of RxJava2 over AsyncTask

Hi, I am reading about rxjava2, which is mainly intended for asynchronous operations. I found that he has an operator concept that AsyncTaskin android does not.

How else rxjava2is different from AsyncTask?

+6
source share
2 answers

RxJava is not "mainly for asynchronous operation." This is only one aspect.

  • RxJava allows you to compose data operations, so that the output of one operation can be used as input for the next. This works similarly to threading.
  • RxJava , . , . RxJava asyncTask .
  • RxJava Flowable, Observable . , .
  • RxJava .

asyncTask .

+12

AsyncTask - , .

AsyncTask:

  • WEB-:

    AsyncTask, AsyncTask Activity/Fragment, .

    :

    / - , , . , ? AsyncTasks, .

  • , - ? , . , , ..

, RxJava

RxJava :

webService.doSomething(someData)
          .observeOn(AndroidSchedulers.mainThread())
          .subscribe(
              result -> resultText.setText("It worked!"),
              e -> handleError(e));

-, -.

public Observable<List<Weather>> getWeatherForLargeUsCapitals() {
  return cityDirectory.getUsCapitals()
                      .flatMap(cityList -> Observable.from(cityList))
                      .filter(city -> city.getPopulation() > 500,000)
                      .flatMap(city -> weatherService.getCurrentWeather(city)) //each runs in parallel
                      .toSortedList((cw1,cw2) -> cw1.getCityName().compare(cw2.getCityName()));
}

, !

+2

All Articles