0

在 RxJava 中,Emitter 接口和 Observer 接口有什么区别?两者都有相同的方法

public interface Emitter<@NonNull T> {

    /**
     * Signal a normal value.
     * @param value the value to signal, not {@code null}
     */
    void onNext(@NonNull T value);

    /**
     * Signal a {@link Throwable} exception.
     * @param error the {@code Throwable} to signal, not {@code null}
     */
    void onError(@NonNull Throwable error);

    /**
     * Signal a completion.
     */
    void onComplete();
}


public interface Observer<@NonNull T> {

    /**
     * Provides the {@link Observer} with the means of cancelling (disposing) the
     * connection (channel) with the {@link Observable} in both
     * synchronous (from within {@link #onNext(Object)}) and asynchronous manner.
     * @param d the {@link Disposable} instance whose {@link Disposable#dispose()} can
     * be called anytime to cancel the connection
     * @since 2.0
     */
    void onSubscribe(@NonNull Disposable d);

    /**
     * Provides the {@link Observer} with a new item to observe.
     * <p>
     * The {@link Observable} may call this method 0 or more times.
     * <p>
     * The {@code Observable} will not call this method again after it calls either {@link #onComplete} or
     * {@link #onError}.
     *
     * @param t
     *          the item emitted by the Observable
     */
    void onNext(@NonNull T t);

    /**
     * Notifies the {@link Observer} that the {@link Observable} has experienced an error condition.
     * <p>
     * If the {@code Observable} calls this method, it will not thereafter call {@link #onNext} or
     * {@link #onComplete}.
     *
     * @param e
     *          the exception encountered by the Observable
     */
    void onError(@NonNull Throwable e);

    /**
     * Notifies the {@link Observer} that the {@link Observable} has finished sending push-based notifications.
     * <p>
     * The {@code Observable} will not call this method if it calls {@link #onError}.
     */
    void onComplete();

}
4

2 回答 2

1

两者都有相同的方法

No.Observer.onSubscribe故意不在Emitter.

Emitter是一个接口,允许回调发出一个项目、一个错误或完成的信号。它用于在generate运算符中产生下一个信号。

由于generate在回调调用之间处理取消,因此没有理由或方法调用onSubscribean Observer,因此为了避免混淆并拥有干净的最小 API,该Observer接口不能使用,Emitter而是添加了专用接口 , 代替。

于 2021-01-15T08:32:11.643 回答
0

当有新事物时,An会Emitter调用它。onNextAnObserver期望onNext在有新内容时调用它。

Emitter知道事件并且可以通过调用它来暴露它们onNext。An想要被告知事件,并在被调用Observer时了解它们。onNext

于 2021-01-15T04:37:15.863 回答