RxJava - 如何停止(和恢复)Hot Observable(间隔)?

时间:2016-12-09 23:29:48

标签: android rx-java reactive-programming stoppropagation rx-java2

我有以下Hot Observable:

org.openqa.selenium.firefox.NotConnectedException: Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms. Firefox console output:
ctExt/content/firefoxextension.png","icon64URL":null,"defaultLocale":{"name":"PDF Architect Converter For Firefox","description":"This extension help you to convert html page to the pdf document.","creator":"pdfforge GmbH","homepageURL":"},"visible":true,"active":false,"userDisabled":true,"appDisabled":true,"descriptor":"C:\\Program Files (x86)\\PDF Architect\\FFPDFArchitectExt","installDate":1395772957003,"updateDate":1395772957003,"applyBackgroundUpdates":1,"bootstrap":false,"skinnable":false,"size":413015,"sourceURI":null,"releaseNotesURI":null,"softDisabled":false,"foreignInstall":true,"hasBinaryComponents":false,"strictCompatibility":false,"locales":[],"targetApplications":[{"id":"{ec8030f7-c20a-464f-9b0e-13a3a9e97384}","minVersion":"4.0","maxVersion":"9.*"}],"targetPlatforms":[],"multiprocessCompatible":false,"signedState":0,"seen":true}
1481279715745 DeferredSave.extensions.json DEBUG Save changes
1481279715745 addons.xpi DEBUG Updating database with changes to installed add-ons
1481279715745 addons.xpi-utils DEBUG Updating add-on states
1481279715747 addons.xpi-utils DEBUG Writing add-ons list
1481279715749 addons.xpi DEBUG Registering manifest for C:\Program Files (x86)\Mozilla Firefox\browser\features\aushelper@mozilla.org.xpi
1481279715750 addons.xpi DEBUG Calling bootstrap method startup on aushelper@mozilla.org version 1.0
1481279715751 addons.xpi DEBUG Registering manifest for C:\Program Files 

然而,我找不到阻止它的好方法。我能够使用hotObservable = Observable.interval(0L, 1L, TimeUnit.SECONDS) .map((t) -> getCurrentTimeInMillis())) takeWhile标记(boolean)部分解决此问题:

runTimer

虽然这种方法中有两件我不喜欢的东西:

  1. 我必须保持旗帜Observable.interval(0L, 1L, TimeUnit.SECONDS) .takeWhile((t) -> runTimer) .map((t) -> getCurrentTimeInMillis())) ,这是我不想要的。
  2. 一旦runTimer变为runTimer,Observable就会完成,这意味着如果我想再次发射,我需要创建一个新的Observable。我不希望这样。我只是希望Observable停止发射物品,直到我告诉它重新开始。
  3. 我希望有这样的事情:

    false

    这样我就不需要保留任何标志,并且observable总是活着的(虽然它可能不会发出事件)。

    我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:7)

一种可能的方法是使用BehaviorSubject和switchMap:

return some_variable;

通过向受试者发送布尔值,可以控制观察者的输出。 BehaviorSubject<Boolean> subject = BehaviorSubject.create(true); hotObservable = subject.distinctUntilChanged().switchMap((on) -> { if (on) { return Observable.interval(0L, 1L, TimeUnit.SECONDS); } else { return Observable.never(); } }).map((t) -> getCurrentTimeInMillis()); 将导致使用该主题创建的任何可观察对象开始发出值。 subject.onNext(true)禁用该流程。

subject.onNext(false)负责在关闭时处理底层的observable。它还使用switchMap来确保它不会进行不必要的切换。

答案 1 :(得分:1)

Mybe你可以用这个

Observable.interval(3, TimeUnit.SECONDS)
        .takeUntil(stop)
        .subscribe(new MyObserver());

Thread.sleep(10000);
stop.onNext(-1);