如何使用连接的可观察对象重放?它总是调用onComplete。我希望能够触发多个具有不同值的事件
,
Observable<String> interval = Observable.just("A", "B");
ConnectableObservable<String> published = interval.publish();
CompositeSubscription mCompositeSubscription = new CompositeSubscription();
mCompositeSubscription.add(published.subscribe(new Observer<String>() {
@Override
public void onCompleted() {
out.println("adsf");
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
out.println(s);
}
}));
published.connect();
// Now I want it to reuse the Observer or Subscriber to get the new events
interval = Observable.just("C", "D");
published = interval.replay();
我不想不断地增加订阅用户来做这件事。我怎样才能做到这一点呢?
谢谢!
看一下主题。使用其中之一(取决于您的需要)代替Observable.just
, publish
和connect
。
Subject<String,String> interval = ReplaySubject.create();
interval.onNext("A");
interval.onNext("B");
//use asObservable before exposing your subject
Observable<String> published = interval.asObserbale;
CompositeSubscription mCompositeSubscription = new CompositeSubscription();
mCompositeSubscription.add(published.subscribe(new Observer<String>() {
@Override
public void onCompleted() {
out.println("adsf");
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
out.println(s);
}
}));
//send new values to Subcribers
interval.onNext("C");
interval.onNext("D");