为什么发布者即使在取消后仍会发送新项目?

Why would publisher send new items even after cancel?

Subscription#cancel 的文档说

Data may still be sent to meet previously signalled demand after calling cancel.

  1. 在哪种情况下,人们会期望发布商继续发送,直到满足先前发出的信号需求?
  2. 另外,取消后不想再寄新的东西怎么办?

除非您正在创建低级运算符或 Publishers,否则您不必担心这一点。

In which scenario would people expect the publisher to continue to send till previous signalled demand is met?

None 的主流 Reactive Streams 库会这样做,因为它们最终会停止发送项目。 RxJava 2 和 Reactor 3 非常热衷于此,因此您很可能在低级别异步发布的取消上有一个额外的项目。 Akka Stream 可能会发出更多信号(上次我检查时,它们混合了控制和项目信号,并且每个流有一个最大同步项目的配置设置,这可能导致在取消生效之前发出多个项目)。

Also, if I don't want any new items to be sent after cancellation, what should I do?

取决于您实施的内容:PublisherSubscriber

Publisher 中,最急切的方法是设置 volatile boolean cancelled field and check that every time 你处于某种发射循环中。

在一个Subscriber中,你可以有一个boolean donefield that is checked in each onXXX so that when you call Subscription.cancel() from onNext, any subsequent call will be ignored