How can I apply a grace time using RX?

独自空忆成欢 提交于 2019-12-10 17:27:38

问题


I have an Observable<Bool> that emits true when an operation begins and false when it ends. I'd like to show a message while the operation is in progress, but only if it takes longer than two seconds to begin. Is there a way I can create an observable that I can bind my message to? Any help much appreciated!


回答1:


If you switchMap (a flatMap where when a second item is emitted from the source the subscription to the original observable is unsubscribed and the subscription moves to the next) you could do something like this:

  1. booleanObservable
  2. .switchMap ( map true to an observable timer of 2 seconds, map false to an empty observable)
  3. .onNext show your message (next won't fire for the empty and a quick response would have cut off the 2 second timer).

Note switchMap is 'switchLatest' in RxSwift.

Could become something like this:

booleanObservable
    .map { inProgress -> Observable<Bool> in
        if inProgress {
            return Observable.just(true).delay(time: 2)
        } else {
            return Observable.just(false)
        }
     }
    .switchLatest()


来源:https://stackoverflow.com/questions/46728626/how-can-i-apply-a-grace-time-using-rx

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!