Flowable.fromPublisher 需要一个发布者,那为什么它接受一个订阅者呢?

Flowable.fromPublisher expects a Publisher, then why does it accept a Subscriber?

方法签名是:

public static <T> Flowable<T> fromPublisher(Publisher<? extends T> source) {...}

但是如果我写这段代码,它会以某种方式工作:

Flowable<String> flowable = Flowable.fromPublisher(subscriber -> {
  subscriber.onNext("But onNext belongs in a subscriber...");
  subscriber.onNext("Which means I am passing a subscriber instead of a publisher");
  subscriber.onNext("What's happening?");
  subscriber.onComplete();
});

我知道我没有正确看待这个问题。有人可以解释传递 Subscriber 而不是 Publisher 的工作原理吗?

这位:

subscriber -> {
  subscriber.onNext("But onNext belongs in a subscriber...");
  subscriber.onNext("Which means I am passing a subscriber instead of a publisher");
  subscriber.onNext("What's happening?");
  subscriber.onComplete();
}

是一个lambda表达式,是Publisher的实现。您的代码等效于以下代码(使用匿名 class):

Flowable<String> flowable = Flowable.fromPublisher(new Publisher<String>() {
  @Override
  public void subscribe(Subscriber<? super String> subscriber) {
    subscriber.onNext("But onNext belongs in a subscriber...");
    subscriber.onNext("Which means I am passing a subscriber instead of a publisher");
    subscriber.onNext("What's happening?");
    subscriber.onComplete();
  }
});