我有一个热门观察者发出的项目,我订阅了一个基本的行动方法(或任何订户)。
我的问题是,当我打电话取消订阅订阅时,我仍然会发现事件。
请参阅下面的测试:
ManualOnSubscribe<Long> emitter = new ManualOnSubscribe<>();
Subscription sub = Observable.create(emitter).subscribe(aLong -> LOGGER.info("receive {}", aLong));
LOGGER.info("emit 1");
emitter.emit(Long.valueOf(1));
LOGGER.info("is unsubscribed ? {}", sub.isUnsubscribed());
sub.unsubscribe();
LOGGER.info("is unsubscribed ? {}", sub.isUnsubscribed());
LOGGER.info("emit 2");
emitter.emit(Long.valueOf(2));
ManualOnSubscribe的代码:
private Set<Subscriber<? super T>> subscribers;
public ManualOnSubscribe() {
subscribers = new HashSet<Subscriber<? super T>>();
}
@Override
public void call(Subscriber<? super T> subscriber) {
subscribers.add(subscriber);
}
public void emit(T item) {
subscribers.stream().forEach(subscriber -> subscriber.onNext(item));
}
当我进行测试时,我有:
(TestUnsubscribe.java:22) - emit 1
(TestUnsubscribe.java:20) - receive 1
(TestUnsubscribe.java:25) - is unsubscribed ? false
(TestUnsubscribe.java:27) - is unsubscribed ? true
(TestUnsubscribe.java:27) - emit 2
(TestUnsubscribe.java:20) - receive 2
当我读到javadoc时,我觉得我做的是正确的,但是它不起作用,有人已经遇到了同样的问题吗? 谢谢你的阅读。