Skip to content

Instantly share code, notes, and snippets.

@anry200
Created March 25, 2016 13:41
Show Gist options
  • Save anry200/648150bd2cf013b040af to your computer and use it in GitHub Desktop.
Save anry200/648150bd2cf013b040af to your computer and use it in GitHub Desktop.
RxUtils
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;
public class RxUtils {
/**
* {@link rx.Observable.Transformer} that transforms the source observable to subscribe in the
* io thread and observe on the Android's UI thread.
*/
private static Observable.Transformer ioToMainThreadSchedulerTransformer;
static {
ioToMainThreadSchedulerTransformer = createIOToMainThreadScheduler();
}
/**
* Get {@link rx.Observable.Transformer} that transforms the source observable to subscribe in
* the io thread and observe on the Android's UI thread.
*
* Because it doesn't interact with the emitted items it's safe ignore the unchecked casts.
*
* @return {@link rx.Observable.Transformer}
*/
@SuppressWarnings("unchecked")
private static <T> Observable.Transformer<T, T> createIOToMainThreadScheduler() {
return tObservable -> tObservable.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
@SuppressWarnings("unchecked")
public static <T> Observable.Transformer<T, T> applyIOToMainThreadSchedulers() {
return ioToMainThreadSchedulerTransformer;
}
public static void unsubscribeIfNotNull(Subscription subscription) {
if (subscription != null) {
subscription.unsubscribe();
}
}
public static CompositeSubscription getNewCompositeSubIfUnsubscribed(CompositeSubscription subscription) {
if (subscription == null || subscription.isUnsubscribed()) {
return new CompositeSubscription();
}
return subscription;
}
}
ApiService.getInstance().apiCall(parameter)
.compose(RxUtil.applyIOToMainThreadSchedulers())
.subscribe(data -> {});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment