问题
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:
- booleanObservable
- .switchMap ( map true to an observable timer of 2 seconds, map false to an empty observable)
- .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