使用
如下代碼,Observable.just()方法創建一個Observable對象
調用subscribe()方法會發出一個包含“野猿新一”內容的事件
通過Action1.call()的回調我們將事件的內容打印出來
Observable.just("野猿新一")
.subscribe(new Action1<String>() {
@Override
public void call(String s) {
Log.d("Himmy", s);
}
});
源碼解析
RxJva現在已經更新到了3.0.0,整個項目的代碼量和複雜度都增加不少,爲了降低理解難度,本文解析的是RxJava1.0.0的源碼,其核心原理是一樣的
由如下源碼可知,just()方法中通過ScalarSynchronousObservable.create創建了一個Observable對象
public final static <T> Observable<T> just(final T value) {
return ScalarSynchronousObservable.create(value);
}
再看下ScalarSynchronousObservable這個類,其實是個Observable的子類,ScalarSynchronousObservable()方法內部其實是通過OnSubscribe來創建Observable
public final class ScalarSynchronousObservable<T> extends Observable<T> {
public static final <T> ScalarSynchronousObservable<T> create(T t) {
return new ScalarSynchronousObservable<T>(t);
}
private final T t;
protected ScalarSynchronousObservable(final T t) {
super(new OnSubscribe<T>() {
@Override
public void call(Subscriber<? super T> s) {
/*
* We don't check isUnsubscribed as it is a significant performance impact in the fast-path use cases.
* See PerfBaseline tests and https://github.com/ReactiveX/RxJava/issues/1383 for more information.
* The assumption here is that when asking for a single item we should emit it and not concern ourselves with
* being unsubscribed already. If the Subscriber unsubscribes at 0, they shouldn't have subscribed, or it will
* filter it out (such as take(0)). This prevents us from paying the price on every subscription.
*/
s.onNext(t);
s.onCompleted();
}
});
this.t = t;
}
public T get() {
return t;
}
}
所以如下兩個方法創建的Observable結果是一樣的,只是just方法幫我們簡化了代碼
// 通過Observable.just創建
Observable observable1 = Observable.just("野猿新一");
// 通過Observable.create和OnSubscribe創建
Observable observable2 = Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
subscriber.onNext("野猿新一");
subscriber.onCompleted();
}
});