我有以下代码来演示问题:
@Component
public class App {
@Autowired S1 s1;
@Autowired S2 s2;
int jobs = 0;
@Scheduled(cron = "0 * * * * ?")
void foo() {
System.out.println("schedule cron job: " + jobs++);
Observable<String> observable = Observable.just("bar");
ConnectableObservable<String> publishedObservable = observable.publish();
publishedObservable.subscribe(s1);
publishedObservable.subscribe(s2);
publishedObservable.connect();
}
}
Subscriber1的:
@Component
public class S1 extends Subscriber<String> {
private AtomicInteger counter = new AtomicInteger(0);
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
System.out.println("S1:::: Times called: " + counter.getAndIncrement() + ", input: " + s);
}
}
subscriber2用户:
@Component
public class S2 extends Subscriber<String> {
private AtomicInteger counter = new AtomicInteger(0);
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
System.out.println("S2:::: Times called: " + counter.getAndIncrement() + ", input: " + s);
}
}
输出将是:
schedule cron job: 0
S1:::: Times called: 0, input: bar
S2:::: Times called: 0, input: bar
schedule cron job: 1
schedule cron job: 2
schedule cron job: 3
schedule cron job: 4
......
为什么每次调用foo方法时都不调用S1和S2? 如何实现?
这是因为rx有些订阅逻辑还是因为这些bean是单例?
答案 0 :(得分:2)
为什么每次调用foo方法时都不调用S1和S2?
RxJava Subscriber
是有状态的,一旦他们消耗了一个序列,他们就不再可用,并将自己报告为取消订阅。再次订阅他们没有任何效果。每次需要订阅源代码时都必须重新创建它们。