如何在不启动新进程的情况下再次订阅Observable?

时间:2015-12-22 12:29:00

标签: java android rx-java rx-android

我有Observable

Observable<String> observable = Observable.create(new Observable.OnSubscribe<String>() {
        @Override
        public void call(Subscriber<? super String> subscriber) {
            if (subscriber.isUnsubscribed()) {
                return;
            }

            for (int i = 0; i < 100; i++) {
               Thread.sleep(100);
              subscriber.onNext("Loading:"+i);
            }
            subscriber.onCompleted();
        }
    });

订阅者

 Subscriber<? super String> sub = new Subscriber<String>() {
                @Override
                public void onCompleted() {
                    pDialog.setMessage("Successfully Done!");
                    pDialog.cancel();
                }

            @Override
            public void onError(Throwable e) {
                pDialog.cancel();
            }

            @Override
            public void onNext(String string) {
                pDialog.setMessage(string);
            }
        };

点击按钮后,我这样做:

  compositeSubscription.add(observable.subscribeOn(Schedulers.newThread()).observeOn(
            AndroidSchedulers.mainThread()).subscribe(sub));

活动:

@Override
protected void onStart() {
    super.onStart();
   compositeSubscription = new CompositeSubscription();
}

 @Override
    protected void onStop() {
        if (!compositeSubscription.isUnsubscribed()&&compositeSubscription.hasSubscriptions())
            compositeSubscription.unsubscribe();
        super.onStop();
    }

单击按钮后,将显示对话框并正在更新消息。

但是如果我最小化应用程序并再次打开它,则会丢失订阅并且消息不会更新,但是进程会继续执行。

如何在不启动新流程的情况下再次订阅Observable?

2 个答案:

答案 0 :(得分:2)

1)您在这里处理冷可观察,这意味着每次订阅时,每个订阅都会调用 OnSubscribe.call()。您可以在此处使用 publish() Observable 转换为 ConnectableObservable 或将 cold 转换为的任何其他运算符热

2)如果您希望 Observable 在从后台返回后继续工作,则 onStart / onStop 不是正确的生命周期回调。我要去那里 onCreate / onDestroy

3)取消订阅不会停止 OnSubscribe.call()执行。最简单的解决方案是检查循环中的 isUnsubscribed()并相应地停止。

答案 1 :(得分:0)

使用Subject

Observable<Long> observable = Observable.interval(100, TimeUnit.MILLISECONDS);

PublishSubject<Object> subject = PublishSubject.create();
observable.subscribe(subject);

Subscription subscription = subject.subscribe(o -> {
    System.out.println("o = " + o);
});

Thread.sleep(500);
subscription.unsubscribe();

Subscription subscription2 = subject.subscribe(o -> {
    System.out.println("continued = " + o);
});

Thread.sleep(500);
subscription.unsubscribe();

这将产生以下输出:

o = 0
o = 1
o = 2
o = 3
o = 4
continued = 5
continued = 6
continued = 7
continued = 8
continued = 9