rxjava 2 flapMap example in Android
Each successive flapMap takes the result from the previous one as the input, multiply it by an integer and passes it as a new input to the next flapMap. For example:
input: 2
1st flapMap: 2 * 2
2nd flapMap: 4 * 3
3rd flapMap: 12 * 4
Final result: 48
private void flapMapEx() { Observable.just(2) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .flatMap(new Function>() { @Override public Observable apply(Integer integer) { Log.d("flatMap", integer + " * 2"); return multiplyInt(integer, 2); } }) .flatMap(new Function >() { @Override public Observable apply(Integer integer) { Log.d("flatMap", integer + " * 3"); return multiplyInt(integer, 3); } }) .flatMap(new Function >() { @Override public Observable apply(Integer integer) { Log.d("flatMap", integer + " * 4"); return multiplyInt(integer, 4); } }) .subscribe(new Observer () { @Override public void onSubscribe(Disposable d) { } @Override public void onComplete() { Log.d("flatMap", "onComplete"); } @Override public void onError(Throwable e) { e.printStackTrace(); Log.d("flatMap", "onError"); } @Override public void onNext(Integer integer) { Log.d("flatMap", "Final result: " + integer.toString()); } }); } private Observable multiplyInt(final Integer integer, final int mulplier) { //simulating a heavy duty computational expensive operation for (int i=0; i<1000000000; i++) {} return Observable.just(new Integer(integer * mulplier)); }
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts