Single will send only one event, either a success or failure event, with no onComplete notification.

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()); }});Copy the code

Call create to create the SingleCreate object

 public static <T> Single<T> create(SingleOnSubscribe<T> source) {
        ...
        return RxJavaPlugins.onAssembly(new SingleCreate<T>(source));
    }
Copy the code
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); }}...Copy the code

Perform to the source. The subscribe (parent); And we can use the Emitter to send data. For example, we’re sending emitters. 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(); } } } } }Copy the code

downstream.onSuccess(value); Send the event to the observer and then call d.dispose(); OnError will not send the event down to the observer. So the event is either onSuccess or onError.

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

    void onSubscribe(@NonNull Disposable d);

    void onSuccess(@NonNull T t);

    void onError(@NonNull Throwable e);
}
Copy the code

Single will only be interested in SingleObserver, which only has success and failure events, such as those that can be used to frame a network and either request success or fail.

Based on the source 2.2.4 version