建议,先去了解观察者模式。
前期工作:引入RX的包
build.gradle脚本里面的
dependencies{
compile ‘io.reactivex:rxjava:1.1.0‘compile ‘io.reactivex:rxandroid:1.1.0‘
} 需要用到的类 Observable Subscriber 第一种写法:1.创建被观察者
Observable<String> observable = Observable.create(new Observable.OnSubscribe<String>() { @Override public void call(Subscriber<? super String> subscriber) { if (!subscriber.isUnsubscribed()) { subscriber.onNext("hello"); subscriber.onNext("hi"); subscriber.onNext("world"); subscriber.onNext("ok"); subscriber.onCompleted(); // 结尾 } }});
2. 定义观察者
Subscriber<String> subscriber = new Subscriber<String>() { @Override public void onCompleted() { Log.e(TAG, "onCompleted"); } @Override public void onError(Throwable e) { Log.e(TAG, "onError"); } @Override public void onNext(String str) { Log.e(TAG, str); }};3.关联被观察者observable.subscribe(subscriber);
第二种写法:
Observable.create(new Observable.OnSubscribe<Integer>() { @Override public void call(Subscriber<? super Integer> subscriber) { if (!subscriber.isUnsubscribed()) { for (int i = 0; i < 10; i++) { subscriber.onNext(i); } subscriber.onCompleted(); } } }).subscribe(new Subscriber<Integer>() { @Override public void onCompleted() { Log.e(TAG, "onCompleted"); } @Override public void onError(Throwable e) { Log.e(TAG, "onError"); } @Override public void onNext(Integer integer) { Log.e(TAG, String.valueOf(integer)); } });}
时间: 2024-12-16 08:50:03