Rxjava2 Single

245 阅读1分钟

Single只会发送1个事件,要么成功要么失败事件,没有onComplete通知。

Single.create(new SingleOnSubscribe<String>() {
            @Override
            public void subscribe(@NotNull SingleEmitter<String> emitter) throws Exception {
                emitter.onSuccess("1");
            }
        }).subscribe(new Consumer<String>() {
            @Override
            public void accept(String str) throws Exception {
                System.out.println(str);

            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                System.out.println(throwable.getMessage());
            }
        });

调用create创造SingleCreate对象

 public static <T> Single<T> create(SingleOnSubscribe<T> source) {
        ...
        return RxJavaPlugins.onAssembly(new SingleCreate<T>(source));
    }
public final class SingleCreate<T> extends Single<T> {

   final SingleOnSubscribe<T> source;

   public SingleCreate(SingleOnSubscribe<T> source) {
       this.source = source;
   }

   @Override
   protected void subscribeActual(SingleObserver<? super T> observer) {
       Emitter<T> parent = new Emitter<T>(observer);
       observer.onSubscribe(parent);

       try {
           source.subscribe(parent);
       } catch (Throwable ex) {
           Exceptions.throwIfFatal(ex);
           parent.onError(ex);
       }
   }
   ...

执行到source.subscribe(parent);时,我们就可以使用emitter发送数据了。 比如我们发送 emitter.onSuccess("1");

@Override
     public void onSuccess(T value) {
         if (get() != DisposableHelper.DISPOSED) {
             Disposable d = getAndSet(DisposableHelper.DISPOSED);
             if (d != DisposableHelper.DISPOSED) {
                 try {
                     if (value == null) {
                         downstream.onError(new NullPointerException("onSuccess called with null. Null values are generally not allowed in 2.x operators and sources."));
                     } else {
                         downstream.onSuccess(value);
                     }
                 } finally {
                     if (d != null) {
                         d.dispose();
                     }
                 }
             }
         }
     }
     

downstream.onSuccess(value);将事件发送给观察者,然后 调用d.dispose();onError就不会将事件下发给观察者了。所以事件要是onSuccess,要么是onError。

public abstract class Single<T> implements SingleSource<T> {
...
}
public interface SingleSource<T> {
    void subscribe(@NonNull SingleObserver<? super T> observer);
}
public interface SingleObserver<T> {

    void onSubscribe(@NonNull Disposable d);

    void onSuccess(@NonNull T t);

    void onError(@NonNull Throwable e);
}

Single只会对SingleObserver感兴趣,SingleObserver只有成功与失败事件,比如可以用来搭建网络框架,要么请求成功,要么失败。

基于源码2.2.4版本