Android 使用RxJava监视蓝牙连接的超时

Android 使用RxJava监视蓝牙连接的超时,android,bluetooth,rx-java,Android,Bluetooth,Rx Java,在我的应用程序中,我正在使用库连接到热敏打印机。我有一个活动,当启动时,尝试自动连接到设备 现在我有了这个功能,我想实现一个超时功能。我认为使用RxJava可以显示倒计时(5秒),然后在时间流逝时向用户显示“重试”按钮。以下是我目前掌握的情况: protected void onAutoConnectStarted() { count = 5; countdown.setText( count.toString() ); countdown.setVisibility(

在我的应用程序中,我正在使用库连接到热敏打印机。我有一个活动,当启动时,尝试自动连接到设备

现在我有了这个功能,我想实现一个超时功能。我认为使用RxJava可以显示倒计时(5秒),然后在时间流逝时向用户显示“重试”按钮。以下是我目前掌握的情况:

protected void onAutoConnectStarted() {
    count = 5;
    countdown.setText( count.toString() );
    countdown.setVisibility( View.VISIBLE );
    retry.setVisibility( View.GONE );

    Observable.interval( 1, TimeUnit.SECONDS )
        .take( 5 )
        .doOnNext( second -> {
            if (bluetoothSPP.getServiceState() == BluetoothState.STATE_CONNECTED) {
                throw new Exception("Break!");
            }
        })
        .subscribeOn( Schedulers.newThread() )
        .observeOn( AndroidSchedulers.mainThread() )
        .subscribe( second -> {
            count--;

            countdown.setText( count.toString() );
            countdown.setVisibility( View.VISIBLE );
            retry.setVisibility( View.GONE );
        }, error -> {
            countdown.setVisibility( View.GONE );
            retry.setVisibility( View.GONE );

            // This is good, we can move on and do stuff
            print();
        }, () -> {
            stopAutoConnect();

            countdown.setVisibility( View.GONE );
            retry.setVisibility( View.VISIBLE );
        });
}
基本上,我想每秒钟更新一次计时器显示。除此之外,如果连接成功或达到5秒(以先到者为准),我希望例程退出


尽管这段代码似乎有效。有更好的方法吗?

看起来你试图在不合适的地方做事情。使用rxjava,您总是有一些好的选择,但在您的情况下,您最好更新计数器
onNext()
,显示retry
onError()
,并继续成功的bt连接
onCompleted()
。例如:

Observable
  .interval(1, TimeUnit.SECONDS)
  .takeUntil(__ -> isBluetoothConnected())
  .takeUntil(Observable
      .timer(5, TimeUnit.SECONDS)
      .flatMap(timeout -> Observable.error(new TimeoutException())))
  .subscribeOn(Schedulers.newThread())
  .observeOn(AndroidSchedulers.mainThread())
  .subscribe(
    secondsPassed -> updateCounter(),              //every second
    error         -> stopConnectingAndShowRetry(), //timeout
    ()            -> print()                       //bt connected
  )

该死!直到我才看到Take。我不会想到你在早些时候提出的逻辑,只是尝试了一下,超时从未发生-根据文档,超时是为每个发射的项目重置的。在这种情况下,超时运算符每秒重置一次!是的,你是对的。我做了一些改变。现在不那么优雅了)