Created
March 25, 2016 13:41
-
-
Save anry200/648150bd2cf013b040af to your computer and use it in GitHub Desktop.
RxUtils
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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