蛋疼!刚开始接触RxJava的朋友们一定会有这样的想法。这货有啥用?看了很多文章抨击RxJava所以就不去了解。但是RxJava发展到现在仍然有不少公司在使用一定是有它存在的道理的,不是教程,不是教程,纯粹分享,map和flatMap的部分看了很多解读,总结了一个比较好理解的,希望对同样困惑的朋友有一丢丢的帮助~
Observable observable = Observable.create(new Observable.OnSubscribe() {
@Override
public void call(Subscriber super String> subscriber) {
subscriber.onNext("1");
subscriber.onNext("2");
subscriber.onCompleted();
}
});
Observer observer = new Observer() {
@Override
public void onCompleted() {
Log.d(TAG, "onCompleted: ");
}
@Override
public void onError(Throwable e) {
Log.d(TAG, "onError: ");
}
@Override
public void onNext(String s) {
Log.d(TAG, "onNext: "+s);
}
};
public abstract class Subscriber implements Observer
使用上与Observer相同,在subscribe的过程中,Observer也会先转换成subscriber
public final Subscription subscribe(final Observer super T> observer) {
if (observer instanceof Subscriber) {
return subscribe((Subscriber super T>)observer);
}
return subscribe(new Subscriber() {
@Override
public void onCompleted() {
observer.onCompleted();
}
@Override
public void onError(Throwable e) {
observer.onError(e);
}
@Override
public void onNext(T t) {
observer.onNext(t);
}
});
}
observable.subscribe(observer);
在被观察者产生事件,以及观察者接收到事件并处理的过程中可以做很多事情,比如转换事件类型、合并多个事件、事件延迟发送等。
Observable.just(1, 2, 3,4)
.subscribe(new Observer() {
@Override
public void onSubscribe(Disposable d) {
Log.d(TAG, "开始采用subscribe连接");
}
// 默认最先调用复写的 onSubscribe()
@Override
public void onNext(Integer value) {
Log.d(TAG, "接收到了事件"+ value );
}
@Override
public void onError(Throwable e) {
Log.d(TAG, "对Error事件作出响应");
}
@Override
public void onComplete() {
Log.d(TAG, "对Complete事件作出响应");
}
});
Observable.timer(2, TimeUnit.SECONDS)
.subscribe(new Observer() {
// 参数说明:
// 参数1 = 第1次延迟时间;
// 参数2 = 间隔时间数字;
// 参数3 = 时间单位;
Observable.interval(3,1,TimeUnit.SECONDS)
.map(new Func1()
.
/**
* Returns an Observable that emits items based on applying a function that you supply to each item emitted
* by the source Observable, where that function returns an Observable, and then merging those resulting
* Observables and emitting the results of this merger.
*
*
*
* - Scheduler:
* - {@code flatMap} does not operate by default on a particular {@link Scheduler}.
*
*
* @param func
* a function that, when applied to an item emitted by the source Observable, returns an
* Observable
* @return an Observable that emits the result of applying the transformation function to each item emitted
* by the source Observable and merging the results of the Observables obtained from this
* transformation
* @see ReactiveX operators documentation: FlatMap
*/
public final Observable flatMap(Func1 super T, ? extends Observable extends R>> func) {
if (getClass() == ScalarSynchronousObservable.class) {
return ((ScalarSynchronousObservable)this).scalarFlatMap(func);
}
return merge(map(func));
}
具体例子
Func1中传入的I是String类型的对象,目标O是Observable,首先将传入的String对象转换为Observable对象,然后这个Obsercable对象开始发送他的事件,也就是List,最终返回的是一个Observable对象,并将其发送的事件(List)交给subscriber中的回调方法进行处理。
.flatMap(new Func1>>()