Observables(被观察者,事件源):发出一系列事件。
Subscribers(观察者):处理这些事件。
一、添加RxJava依赖
implementation 'io.reactivex:rxjava:1.0.14' implementation 'io.reactivex:rxandroid:1.0.1'
二、初识Observables和Subscribers
Observable<String> observable = Observable.create(new Observable.OnSubscribe<String>() { @Override public void call(Subscriber<? super String> subscriber) { subscriber.onNext("风水宝地九分裤"); subscriber.onCompleted(); } }); Subscriber subscriber = new Subscriber() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(Object o) { Log.d("WY", String.valueOf(o)); } }; observable.subscribe(subscriber);//被观察者订阅观察者
简化Subscriber,我们其实并不关心OnComplete和OnError,我们只需要在onNext的时候做一些处理,这时候就可以使用Action1类。
Observable observable = Observable.just("hee"); Action1<String> action1 = new Action1<String>() { @Override public void call(String s) { Log.d("WY", s); } }; Action1<Throwable> action11 = new Action1<Throwable>() { @Override public void call(Throwable o) { } }; Action0 action0 = new Action0() { @Override public void call() { } }; observable.subscribe(action1, action11, action0);
以上,还可以简略成
Observable.just("ddd").subscribe(new Action1<String>() { @Override public void call(String s) { Log.d("WY", s); } });
三、变换
map操作符实现变换,让Subscribers更加轻量级。
Observable.just(110).map(new Func1<Integer, String>() { @Override public String call(Integer s) { return String.valueOf(s) + "s"; } }).subscribe(new Action1<String>() { @Override public void call(String t) { Log.d("WY", t); } });
Observable.just("110").map(new Func1<String, Integer>() { @Override public Integer call(String s) { return s.hashCode(); } }).map(new Func1<Integer, String>() { @Override public String call(Integer integer) { return String.valueOf(integer) + "s"; } }).subscribe(new Action1<String>() { @Override public void call(String s) { Log.d("WY", s); } });