Skip to content

Instantly share code, notes, and snippets.

@alexfu
Last active February 7, 2021 15:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alexfu/667b4ee05361c02f0929 to your computer and use it in GitHub Desktop.
Save alexfu/667b4ee05361c02f0929 to your computer and use it in GitHub Desktop.
Helpful RxJava functions for daily use
/**
* Transforms an observable to run on a new thread
* and to be observed on Androids main thread.
*/
public static <T> Observable.Transformer<T, T> androidAsync() {
return new Observable.Transformer<T, T>() {
@Override
public Observable<T> call(Observable<T> observable) {
return observable
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread());
}
};
}
/**
* Provides an equivalent of mapWithIndex operation.
*
* Usage:
* List<String> names = Arrays.asList("Joe", "Bob", "Dave");
* mapWithIndex(names, new Func2<String, Integer, String>() {
* @Override
* public String call(String name, Integer index) {
* if (index > 0) {
* return name + " !!";
* } else {
* return name;
* }
* }
* });
*/
public static <T,R> Observable<R> mapWithIndex(Collection<T> collection, Func2<T, Integer, R> mapFunc) {
return Observable.from(collection).zipWith(Observable.range(0, collection.size()), mapFunc);
}
/**
* Throws an exception; for testing purposes.
*/
public static <T> Observable<T> throwsException() {
return Observable.create(new Observable.OnSubscribe<T>() {
@Override
public void call(Subscriber<? super T> subscriber) {
subscriber.onError(new Exception("Mock exception"));
}
});
}
/**
* Unwraps a list of items and emits them one by one.
*/
public static <T> Func1<List<T>, Observable<T>> unwrapList() {
return new Func1<List<T>, Observable<T>>() {
@Override
public Observable<T> call(List<T> list) {
return Observable.from(list);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment