RxJava Github地址:https://github.com/ReactiveX/RxJava
首先引入库文件(当前最新版本为2.1.4)
dependencies {
...
compile 'io.reactivex.rxjava2:rxjava:2.1.4'
}
先来一个简单例子
例1
//创建被观察者
Observable observable = Observable.create(new Observable.OnSubscribe() {
@Override
public void call(Subscriber super String> subscriber) {
subscriber.onNext("1");
subscriber.onNext("2");
subscriber.onNext("3");
subscriber.onCompleted();
}
});
//创建观察者
Observer observer = new Observer() {
@Override
public void onCompleted() {
System.out.println("onCompleted");
}
@Override
public void onError(Throwable e) {
System.out.println(e);
}
@Override
public void onNext(String s) {
System.out.println(s);
}
};
//订阅
observable.subscribe(observer);
结果:
1
2
3
onCompleted
(1)我们先来看看第一步,创建被观察者:
Observable.create方法(2.0后已经Deprecated)
@Deprecated
public static Observable create(OnSubscribe f) {
return new Observable(RxJavaHooks.onCreate(f));
}
OnSubscribe是接口, 继承了Action1
注意这里的参数从转换为了Subscriber super T>
public interface OnSubscribe extends Action1> {
}
Action1接口,只有一个call方法 有一个参数,无返回值
public interface Action1 extends Action {
void call(T t);
}
这就与以上例1中的创建观察者相对应了, Observable.create()传入泛型为String的onSubscribe, 并实现接口call(T t),这里的T也变为了Subscriber super String>类型
Observable observable = Observable.create(new Observable.OnSubscribe() {
@Override
public void call(Subscriber super String> subscriber) {
}
});
(2)我们再来看看Observer
public interface Observer {
//通知观察者,被观察者完成了基于推送的通知。onCompleted()与onError()设计上只会有一个被调用
void onCompleted();
//通知观察者,出错了,一但出错,被观察者将不再继续调用接下来的步骤,如onNext, onCompleted
void onError(Throwable e);
//向观察者提供新的观察事件
void onNext(T t);
}
(3)最后实现订阅关系,以原代码角度来分析,如何将Observable与Observer相关联
Observable.create()时,新建了一个Observable实例
@Deprecated
public static Observable create(OnSubscribe f) {
return new Observable(RxJavaHooks.onCreate(f));
}
构造方法中只是将onSubscribe对象保存起来
protected Observable(OnSubscribe f) {
this.onSubscribe = f;
}
我们再来看看Observable.subscribe()方法, 这里判断observer是不是Subscriber的实例,不是的话通过新建ObserverSubscriber类来转换成为Subscriber,所以最终都是调用subscribe(Subscriber)
Subscriber 与Observer类似, 实现了Observer, 同时也实现了Subscription, 多了两个方法:unsubscribe(), isUnsubscribed()
public final Subscription subscribe(final Observer super T> observer) {
if (observer instanceof Subscriber) {
return subscribe((Subscriber super T>)observer);
}
if (observer == null) {
throw new NullPointerException("observer is null");
}
return subscribe(new ObserverSubscriber(observer));
}
public final class ObserverSubscriber extends Subscriber {
final Observer super T> observer;
public ObserverSubscriber(Observer super T> observer) {
this.observer = observer;
}
@Override
public void onNext(T t) {
observer.onNext(t);
}
@Override
public void onError(Throwable e) {
observer.onError(e);
}
@Override
public void onCompleted() {
observer.onCompleted();
}
}
最后调用 了Observable.subscribe(subscriber, this),注意这里关键的this
public final Subscription subscribe(Subscriber super T> subscriber) {
return Observable.subscribe(subscriber, this);
}
static Subscription subscribe(Subscriber super T> subscriber, Observable observable) {
//......
// Subscriber类中的onStart()为空实现, 在Observer所有方法之前被调用。
subscriber.onStart();
//......
try {
//这里的observable实际就是当前对象,在这里调用了当前对象中onSubscribe的call.并将例一中的observer 以Subscriber封装后的实例作为call的参数返回。
RxJavaHooks.onObservableStart(observable, observable.onSubscribe).call(subscriber);
return RxJavaHooks.onObservableReturn(subscriber);
} catch (Throwable e) {
//......
subscriber.onError(RxJavaHooks.onObservableError(e));
//最后返回未取消订阅的Subscription对象
return Subscriptions.unsubscribed();
}
}
简单来看一看RxJavaHooks中的onObservableStart方法
public static Observable.OnSubscribe onObservableStart(Observable instance, Observable.OnSubscribe onSubscribe) {
Func2 f = onObservableStart;
if (f != null) {
//经过一系列调用, 最终还是返回的onSubscribe本身,参考下面的分析
return f.call(instance, onSubscribe);
}
//如果onObservableStart为null便将传进来的onSubscribe原封返回
return onSubscribe;
}
来简单分析一下f.call();
static void init() {
//......
onObservableStart = new Func2() {
@Override
public Observable.OnSubscribe call(Observable t1, Observable.OnSubscribe t2) {
return RxJavaPlugins.getInstance().getObservableExecutionHook().onSubscribeStart(t1, t2);
}
};
//......
}
@Deprecated
public OnSubscribe onSubscribeStart(Observable extends T> observableInstance, final OnSubscribe onSubscribe) {
return onSubscribe;//将传进来的onSubscribe原封返回
}
至此,例1所有代码便分析完成。
例1步骤可以简化成以下
Observable.create(new Observable.OnSubscribe() {
@Override
public void call(Subscriber super String> subscriber) {
subscriber.onNext("1");
subscriber.onNext("2");
subscriber.onNext("3");
subscriber.onCompleted();
}
}).subscribe(new Observer() {
@Override
public void onCompleted() {
System.out.println("onCompleted");
}
@Override
public void onError(Throwable e) {
System.out.println(e);
}
@Override
public void onNext(String s) {
System.out.println(s);
}
});
或lambda表达式:
Observable.create((Observable.OnSubscribe) subscriber -> {
subscriber.onNext("1");
subscriber.onNext("2");
subscriber.onNext("3");
subscriber.onCompleted();
}).subscribe(new Observer() {
@Override
public void onCompleted() {
System.out.println("onCompleted");
}
@Override
public void onError(Throwable e) {
System.out.println(e);
}
@Override
public void onNext(String s) {
System.out.println(s);
}
});
操作符
这和java8中的Stream很相似,可参考我的另一篇文章《函数式编程 Lambda及Stream》
下面举几个常用的例子
from
接收数组,实现Iterable的子类对象,及Future对象
String[] array = new String[]{"a", "b", "c"};
Observable.from(Arrays.asList(array))
.subscribe(new Subscriber() {
@Override
public void onCompleted() {
System.out.println("onCompleted");
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
System.out.println(s);
}
});
结果:
a
b
c
onCompleted
just
看原码也是调用的 from((T[])new Object[] { })
Observable.just("1", "2", "3")
.subscribe(new Subscriber() {
@Override
public void onCompleted() {
System.out.println("onCompleted");
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
System.out.println(s);
}
});
结果:
1
2
3
onCompleted
defer 延迟
- 即用普通的创建Observable方法
private static String string = "0";
public static void main(String[] args) {
Observable observable = Observable.just(string);
string = "1";
observable.subscribe(System.out::println);
}
结果:0
- 使用defer创建Observable
private static String string = "0";
public static void main(String[] args) {
Observable observable = Observable.defer(() -> Observable.just(string));
string = "1";
observable.subscribe(System.out::println);
}
结果:1
封装时可先使用defer,后面调用时便会根据不同的参数创建相应的新的Observable
map 变换
接收一个Func1类型的参数(一个参数,一个返回值 )
String[] array = new String[]{"a", "b", "c"};
Observable.from(array)
.map(String::toUpperCase)
.subscribe(new Subscriber() {
@Override
public void onCompleted() {
System.out.println("onCompleted");
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
System.out.println(s);
}
});
结果:
A
B
C
onCompleted
flatMap变换
以原有Observable为基础,将发射的每一条数据再分成若干个Observable,最后合并,这就是flat的意思,压平
注意这里与map不同的是,返回值是一个Observable对象。
String[] array = new String[]{"aa", "bbb", "cc"};
Observable.from(array)
.map(String::toUpperCase)
.flatMap(s -> {
List singleLetter = new ArrayList();
for (int i = 0; i < s.length(); i++) {
singleLetter.add(String.valueOf(s.charAt(i)));
}
return Observable.from(singleLetter);
})
.subscribe(new Subscriber() {
@Override
public void onCompleted() {
System.out.println("onCompleted");
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
System.out.println(s);
}
});
结果:
A
A
B
B
B
C
C
onCompleted
scan 累加器
由初始值与累加器构成
-
接收一个Func2
类型参数
String[] array = new String[]{"aa", "bbb", "cc"};
Observable.from(array)
.map(String::toUpperCase)
.flatMap(s -> {
List singleLetter = new ArrayList();
for (int i = 0; i < s.length(); i++) {
singleLetter.add(String.valueOf(s.charAt(i)));
}
return Observable.from(singleLetter);
})
.scan(((s1, s2) -> s1 + s2))
.subscribe(new Subscriber() {
@Override
public void onCompleted() {
System.out.println("onCompleted");
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
System.out.println(s);
}
});
结果:
A
AA
AAB
AABB
AABBB
AABBBC
AABBBCC
onCompleted
在未赋初值的情况下,是不调用该方法的(看下图,scan方法被调用前,Console面板中已经显示出发射的第一条数据。)
发射的第一条数据会作为初始值,发射第二条数据时调用该方法并将初始值传给s1, 将第二条数据传给s2
并将结果作为下一条数据的初始值。
-
接收(R initialValue, Func2
accumulator) 两个参数
String[] array = new String[]{"aa", "bbb", "cc"};
Observable.from(array)
.map(String::toUpperCase)
.flatMap(s -> {
List singleLetter = new ArrayList();
for (int i = 0; i < s.length(); i++) {
singleLetter.add(String.valueOf(s.charAt(i)));
}
return Observable.from(singleLetter);
})
.scan("-", ((s1, s2) -> s1 + s2))
.subscribe(new Subscriber() {
@Override
public void onCompleted() {
System.out.println("onCompleted");
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
System.out.println(s);
}
});
结果:
- //在scan被第一次调用前,已经被打印出来
-A
-AA
-AAB
-AABB
-AABBB
-AABBBC
-AABBBCC
onCompleted
filter 过滤出符合条件的
参数为Func1 super T, Boolean>, 返回布尔值
Observable.from(array)
.filter(s -> s.length()<=2)
.subscribe(new Subscriber() {
@Override
public void onCompleted() {
System.out.println("onCompleted");
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
System.out.println(s);
}
});
结果:
aa
cc
onCompleted
take
String[] array = new String[]{"aa", "bbb", "cc"};
Observable.from(array)
.map(String::toUpperCase)
.flatMap(s -> {
List singleLetter = new ArrayList();
for (int i = 0; i < s.length(); i++) {
singleLetter.add(String.valueOf(s.charAt(i)));
}
return Observable.from(singleLetter);
})
.take(5)//取出5个数据
.subscribe(new Subscriber() {
@Override
public void onCompleted() {
System.out.println("onCompleted");
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
System.out.println(s);
}
});
结果:
A
A
B
B
B
onCompleted
takeFirst
String[] array = new String[]{"aa", "bbb", "cccc", "dddd"};
Observable.from(array)
.map(String::toUpperCase)
.takeFirst(s -> s.length()==4)
.subscribe(new Subscriber() {
@Override
public void onCompleted() {
System.out.println("onCompleted");
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
System.out.println(s);
}
});
结果:
CCCC
onCompleted
takeLast
Observable.from(array)
.map(String::toUpperCase)
.flatMap(s -> {
List singleLetter = new ArrayList();
for (int i = 0; i < s.length(); i++) {
singleLetter.add(String.valueOf(s.charAt(i)));
}
return Observable.from(singleLetter);
})
.takeLast(2) // 取出最后2个数据
.subscribe(new Subscriber() {
@Override
public void onCompleted() {
System.out.println("onCompleted");
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
System.out.println(s);
}
});
结果:
C
C
onCompleted
take与takeLast以时间为限制取数据
public final Observable take(long time, TimeUnit unit) //只取time时间内发射的数据
public final Observable takeLast(long time, TimeUnit unit) //只取time时间结束前的数据
first
- public final Observable
first() {
String[] array = new String[]{"aa", "bbb", "cccc", "dddd"};
Observable.from(array)
.map(String::toUpperCase)
.first()
.subscribe(new Subscriber() {
@Override
public void onCompleted() {
System.out.println("onCompleted");
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
System.out.println(s);
}
});
结果:
AA
onCompleted
- public final Observable
first(Func1 super T, Boolean> predicate) {
String[] array = new String[]{"aa", "bbb", "cccc", "dddd"};
Observable.from(array)
.map(String::toUpperCase)
.first(s -> s.length()==4)
.subscribe(new Subscriber() {
@Override
public void onCompleted() {
System.out.println("onCompleted");
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
System.out.println(s);
}
});
结果:
CCCC
onCompleted
- public final Observable
firstOrDefault(T defaultValue) {
String[] array = new String[]{};
Observable.from(array)
.map(String::toUpperCase)
.firstOrDefault("null")
.subscribe(new Subscriber() {
@Override
public void onCompleted() {
System.out.println("onCompleted");
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
System.out.println(s);
}
});
结果:
null
onCompleted
- public final Observable
firstOrDefault(T defaultValue, Func1 super T, Boolean> predicate) {
String[] array = new String[]{"aa", "bbb", "cccc", "dddd"};
Observable.from(array)
.map(String::toUpperCase)
.firstOrDefault("null", s -> s.equals("fuck"))
.subscribe(new Subscriber() {
@Override
public void onCompleted() {
System.out.println("onCompleted");
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
System.out.println(s);
}
});
结果:
null
onCompleted
skip
String[] array = new String[]{"aa", "bbb", "cccc", "dddd"};
Observable.from(array)
.map(String::toUpperCase)
.skip(2)
.subscribe(new Subscriber() {
@Override
public void onCompleted() {
System.out.println("onCompleted");
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
System.out.println(s);
}
});
结果:
CCCC
DDDD
onCompleted
skipLast
String[] array = new String[]{"aa", "bbb", "cccc", "dddd"};
Observable.from(array)
.map(String::toUpperCase)
.skipLast(2)
.subscribe(new Subscriber() {
@Override
public void onCompleted() {
System.out.println("onCompleted");
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
System.out.println(s);
}
});
结果:
AA
BBB
onCompleted
skipWhile
String[] array = new String[]{"aa", "bbb", "cccc", "dddd"};
Observable.from(array)
.map(String::toUpperCase)
.skipWhile(s -> s.length()<4)
.subscribe(new Subscriber() {
@Override
public void onCompleted() {
System.out.println("onCompleted");
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
System.out.println(s);
}
});
结果:
CCCC
DDDD
onCompleted
distinct 去重
String[] array = new String[]{"aa", "aa", "cccc", "dddd"};
Observable.from(array)
.map(String::toUpperCase)
.distinct()
.subscribe(new Subscriber() {
@Override
public void onCompleted() {
System.out.println("onCompleted");
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
System.out.println(s);
}
});
结果:
AA
CCCC
DDDD
onCompleted
elementAt
String[] array = new String[]{"a", "bb", "ccc", "dddd"};
Observable.from(array)
.map(String::toUpperCase)
.elementAt(2)
.subscribe(new Subscriber() {
@Override
public void onCompleted() {
System.out.println("onCompleted");
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
System.out.println(s);
}
});
结果:
CCC
onCompleted
merge 合并数据源
Observable justA = Observable.just("a1", "a2", "a3");
Observable justB = Observable.just("b1", "b2", "b3");
Observable.merge(justB,justA)
.map(String::toUpperCase)
.subscribe(new Subscriber() {
@Override
public void onCompleted() {
System.out.println("onCompleted");
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
System.out.println(s);
}
});
结果:
B1
B2
B3
A1
A2
A3
onCompleted
zip 合并数据
Observable justA = Observable.just("a1", "a2", "a3");
Observable justB = Observable.just("b1", "b2", "b3", "b4");
Observable.zip(justA,justB,(s1, s2) -> s1+s2)
.map(String::toUpperCase)
.subscribe(new Subscriber() {
@Override
public void onCompleted() {
System.out.println("onCompleted");
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
System.out.println(s);
}
});
结果:
A1B1
A2B2
A3B3
onCompleted
startWith
Observable justA = Observable.just("a1", "a2", "a3");
Observable justB = Observable.just("b1", "b2", "b3", "b4");
Observable.zip(justA,justB,(s1, s2) -> s1+s2)
.map(String::toUpperCase)
.startWith("fuck")
.subscribe(new Subscriber() {
@Override
public void onCompleted() {
System.out.println("onCompleted");
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
System.out.println(s);
}
});
结果:
fuck
A1B1
A2B2
A3B3
onCompleted
empty
创建一个不发射任何数据但是正常终止的Observable
Observable.empty().subscribe(new Subscriber
never
Observable.never().subscribe(new Subscriber() {
@Override
public void onCompleted() {
System.out.println("onCompleted");
}
@Override
public void onError(Throwable e) {
System.out.println(e);
}
@Override
public void onNext(Object o) {
System.out.println(o);
}
});
结果什么都没有
原码分析:
public static Observable never() {
return NeverObservableHolder.instance();
}
public enum NeverObservableHolder implements OnSubscribe {
INSTANCE
;
static final Observable NEVER = Observable.unsafeCreate(INSTANCE);
@SuppressWarnings("unchecked")
public static Observable instance() {
return (Observable)NEVER;
}
@Override
public void call(Subscriber super Object> child) {
// deliberately no op //什么也没做
}
}
range
Observable.range(10, 4).subscribe(System.out::println);
结果:
10
11
12
13
interval
Observable.interval(1, TimeUnit.SECONDS, Schedulers.trampoline()).subscribe(System.out::println);
结果:从0开始每一秒按顺序输出
注意,这里需要设置Schedulers.trampoline(),在当前线程将任务插入队列中。
timer
Observable.timer(3, TimeUnit.SECONDS, Schedulers.trampoline()).subscribe(System.out::println);
结果:三秒后输出0后结束
delay
String[] arrays = new String[]{"1", "2", "3", "4"};
Observable.from(arrays).delay(1, TimeUnit.SECONDS, Schedulers.trampoline()).subscribe(System.out::println);
结果:运行后,一秒后输出1, 每一少输出下一个,输出4再一秒后结束
contains
String[] arrays = new String[]{"1", "2", "3", "4"};
Observable.from(arrays).contains("1").subscribe(System.out::println);
结果:true
all
Integer[] ints = new Integer[]{1, 2, 3, 4};
Observable.from(ints).all(integer -> integer < 3).subscribe(System.out::println);
结果:false
isEmpty
String[] arrays = new String[]{};
Observable.from(arrays).isEmpty().subscribe(System.out::println);
结果:true
exists
Integer[] ints = new Integer[]{1, 2, 3, 4};
Observable.from(ints).exists(integer -> integer > 3).subscribe(System.out::println);
结果:true
count
Integer[] ints = new Integer[]{1, 2, 3, 4, 1};
Observable.from(ints).count().subscribe(System.out::println);
结果:5
reduce 与scan相似,不同的是直接输出结果。
Integer[] ints = new Integer[]{1, 2, 3, 4};
Observable.from(ints).reduce((integer, integer2) -> integer + integer2).subscribe(System.out::println);
Observable.from(ints).reduce(10, (integer, integer2) -> integer + integer2).subscribe(System.out::println);
结果:
10
20
collect
与reduce相似, 但collect是用来将源Observable发射的数据给收集到一个数据结构里面
Integer[] ints = new Integer[]{1, 2, 3, 4};
Observable.from(ints)
// .collect((Func0>) ArrayList::new, (list, integer) -> list.add(integer))
.collect((Func0>) ArrayList::new, ArrayList::add)
.subscribe(System.out::println);
buffer
Observable.interval(1, TimeUnit.SECONDS, Schedulers.trampoline())
.buffer(3)
.subscribe(System.out::println);
结果:每三个放入缓存再输出
[0, 1, 2]
[3, 4, 5]
[6, 7, 8]
[9, 10, 11]
[12, 13, 14]
[15, 16, 17]
。。。
Observable.interval(1, TimeUnit.SECONDS, Schedulers.trampoline())
.buffer(3, 2) //(多少为一组, 生成新的buffer的间隔)
.subscribe(System.out::println);
结果:
[0, 1, 2]
[2, 3, 4]
[4, 5, 6]
[6, 7, 8]
[8, 9, 10]
[10, 11, 12]
。。。
RxJava1.0 与RxJava2.0区别:
- Rxjava1.0资源库都在rx包下,而RxJava2.0都在io.reactivex包下
import rx.Observable;
import rx.Subscriber;
---------------------
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.annotations.NonNull;