rxjava 2 flapMap with filter example in Android
The following code takes a list of integers, the first flapMap passes each integer in the list to the filter one at a time, the filter filters out odd numbers or passes it to the next flapMap if it is an even number.
Input: 1,2,3,4,5,6,7,8,9
Filter out odd numbers 1, 3, 5, 6, 9
Pass down the even numbers 2, 4, 6, 8 to the last flatMap
The last flapMap multiply each even number by 2
The onNext in the subscribe prints 4, 8, 12, 16 one by one
private void flapMapEx() { Listints = new ArrayList<>(); for (int i=1; i<10; i++) { ints.add(new Integer(i)); } Log.d("flatMap", "1,2,3,4,5,6,7,8,9"); Observable.just(ints) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .flatMap(new Function , Observable
>() { @Override public Observable apply(List ints) { return Observable.fromIterable(ints); } }) .filter(new Predicate () { @Override public boolean test(Integer integer) { Log.d("flatMap", "filter out odd numbers........."); return integer.intValue() % 2 == 0; } }) .flatMap(new Function >() { @Override public Observable apply(Integer integer) { //simulating a heavy duty computational expensive operation for (int i = 0; i < 1000000000; i++) { } return multiplyInt(integer, 2); } }) .subscribe(new Observer () { @Override public void onSubscribe(Disposable d) { } @Override public void onComplete() { } @Override public void onError(Throwable e) { e.printStackTrace(); } @Override public void onNext(Integer integer) { Log.d("flatMap", "onNext: " + integer.toString()); } }); }
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts