RxJava - ConnectableObservable,断开连接和重新连接

时间:2017-04-15 10:33:14

标签: java android rx-java rx-android

我正在尝试从"断开连接"复制示例代码。第here节。

  

断开

     

正如我们在connect的签名中看到的那样,此方法返回订阅,就像Observable.subscribe一样。您可以使用该引用来终止ConnectableObservable的订阅。这将阻止事件传播给观察者,但它不会取消订阅ConnectableObservable。 如果再次调用connect,ConnectableObservable将启动新订阅,旧观察者将再次开始接收值。

ConnectableObservable<Long> connectable = Observable.interval(200, TimeUnit.MILLISECONDS).publish();
Subscription s = connectable.connect();

connectable.subscribe(i -> System.out.println(i));

Thread.sleep(1000);
System.out.println("Closing connection");
s.unsubscribe();

Thread.sleep(1000);
System.out.println("Reconnecting");
s = connectable.connect();

输出

0
1
2
3
4
Closing connection
Reconnecting
0
1
2
...

使用RxJava 2.0.8,我有:

    ConnectableObservable<Long> connectable = Observable.interval(200, TimeUnit.MILLISECONDS).publish();
    Disposable s = connectable.connect();

    connectable.subscribe(new Observer<Long>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(Long aLong) {
            Log.d("test", "Num: " + aLong);
        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onComplete() {

        }
    });

    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    Log.d("test", "Closing connection");
    s.dispose();

    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    Log.d("test", "Reconnecting...");
    connectable.connect();

输出

Num: 0
Num: 1
Num: 2
Num: 3
Num: 4
Closing connection
Reconnecting...

提前致谢....

1 个答案:

答案 0 :(得分:4)

似乎RxJava没有采用这种行为。工作示例来自Rx.NET。见https://github.com/ReactiveX/RxJava/issues/4771