Created
February 16, 2017 19:38
-
-
Save kwong93/b11a80ab982c8fd2992dc46061007357 to your computer and use it in GitHub Desktop.
RxJava flatMap single
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
/** | |
* Do 1 heavy operation, when successful, fire 2 more heavy operations sequentially that use the first operation's data | |
*/ | |
private List<String> getHeavyList() { | |
List<String> list = new ArrayList<>(); | |
list.add("First string"); | |
list.add("Second string"); | |
list.add("Third string"); | |
return list; | |
} | |
private int getIntFromList(List<String> strings) { | |
return 1; | |
} | |
private boolean getBoolFromList(List<String> strings) { | |
return true; | |
} | |
Single<List<String>> heavyOperationObservable = Single.fromCallable(new Callable<List<String>>() { | |
@Override | |
public List<String> call() { | |
return getHeavyList(); | |
} | |
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()); | |
heavyOperationObservable.subscribeWith(new DisposableSingleObserver<List<String>>() { | |
@Override | |
public void onSuccess(final List<String> strings) { | |
final Single<Integer> singleInt = Single.fromCallable(new Callable<Integer>() { | |
@Override | |
public Integer call() { | |
return getIntFromList(strings); | |
} | |
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()); | |
final Single<Boolean> singleBoolean = Single.fromCallable(new Callable<Boolean>() { | |
@Override | |
public Boolean call() throws Exception { | |
return getBoolFromList(strings); | |
} | |
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()); | |
singleInt.flatMap(new Function<Integer, Single<Boolean>>() { | |
@Override | |
public Single<Boolean> apply(@io.reactivex.annotations.NonNull Integer integer) throws Exception { | |
return singleBoolean; | |
} | |
}).subscribeWith(new DisposableSingleObserver<Boolean>() { | |
@Override | |
public void onSuccess(Boolean aBoolean) { | |
Log.i("RxJava", "boolean: " + aBoolean); | |
} | |
@Override | |
public void onError(Throwable e) { | |
} | |
}); | |
} | |
@Override | |
public void onError(Throwable e) { | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment