04_RxJava 組合操作符示例
阿新 • • 發佈:2018-11-11
package com.gdc.rxjava; import rx.Observable; import rx.Subscriber; import rx.functions.Func2; public class TestCombining { public static void main(String[] args) { // testZip(); // testMerge(); // startWith(); testCombineLatest(); } private static void testZip() { Observable<Integer> observable1 = Observable.just(10, 20, 30); Observable<Integer> observable2 = Observable.just(4, 8, 12, 16); Observable.zip(observable1, observable2, new Func2<Integer, Integer, Integer>() { @Override public Integer call(Integer arg0, Integer arg1) { return arg0 + arg1; } }).subscribe(new Subscriber<Integer>() { @Override public void onCompleted() { System.out.println("onCompleted()"); } @Override public void onError(Throwable arg0) { System.out.println("onError():" + arg0); } @Override public void onNext(Integer arg0) { System.out.println("onNext():" + arg0); } }); } private static void testMerge() { Observable<Integer> odds = Observable.just(1, 3, 5); Observable<Integer> events = Observable.just(2, 4, 6); Observable.merge(odds, events).subscribe(new Subscriber<Integer>() { @Override public void onCompleted() { System.out.println("onCompleted()"); } @Override public void onError(Throwable arg0) { System.out.println("onError():" + arg0); } @Override public void onNext(Integer arg0) { System.out.println("onNext():" + arg0); } }); } private static void startWith() { Observable<Integer> first = Observable.just(1, 3, 5); Observable<Integer> second = Observable.just(2, 4, 6); first.startWith(second).subscribe(new Subscriber<Integer>() { @Override public void onCompleted() { System.out.println("onCompleted()"); } @Override public void onError(Throwable arg0) { System.out.println("onError():" + arg0); } @Override public void onNext(Integer arg0) { System.out.println("onNext():" + arg0); } }); } private static void testCombineLatest() { Observable<Integer> first = Observable.just(1, 3, 5); Observable<Integer> second = Observable.just(2, 4, 6); first.combineLatest(first, second, new Func2<Integer, Integer, Integer>() { @Override public Integer call(Integer arg0, Integer arg1) { System.out.println("arg0:" + arg0 + " arg1:" + arg1); return arg0 + arg1; } }).subscribe(new Subscriber<Integer>() { @Override public void onCompleted() { System.out.println("onCompleted()"); } @Override public void onError(Throwable arg0) { System.out.println("onError():" + arg0); } @Override public void onNext(Integer arg0) { System.out.println("onNext():" + arg0); } }); } }