0

In RxJava/RxAndroid, you often need to enforce the threading especially when doing network operations, for example:

Single.fromCallable(/*download*/)
      .subscribeOn(Schedulers.io())
      .observeOn(AndroidSchedulers.mainThread())

Support the single is inside a static method or a method, which one of the following makes more sense:

public static Single<File> download(URL url) {
      return Single.fromCallable(/*download*/);
}

public static Single<File> download(URL url) {
     return Single.fromCallable(/*download*/)
      .subscribeOn(Schedulers.io())
      .observeOn(AndroidSchedulers.mainThread())
}

Basically, whose responsibility it is to enforce the threading, the callers' or the callee's and why?

Cheng Xu
  • 164
  • 9
  • It depend on your convention. You can comment on the method that it will run on IO thread or change its name to `downloadOnIO` directly. – Dean Xu Jun 17 '17 at 06:18

1 Answers1

1

It makes more sense to only handle the subscription part with the source. If the thread doesn't matter at all, you can skip it as well. Otherwise you know the requirements to the thread exactly at this place.

public static Single<File> download(URL url) {
     return Single.fromCallable(/*download*/)
      .subscribeOn(Schedulers.io());
}

The observeOn() operator should be used when you consume the events and have specific requirements to the thread at this place.

download(url).observeOn(AndroidSchedulers.mainThread()).subscribe();

Also you could provide a possibility to define it with the method or use other naming conventions like downloadOnIo.

public static Single<File> download(URL url, Scheduler subscribeOn) {
     return Single.fromCallable(/*download*/)
      .subscribeOn(subscribeOn);
}
tynn
  • 38,113
  • 8
  • 108
  • 143