如何使用 RX 应用宽限时间? [英] How can I apply a grace time using RX?
问题描述
我有一个 Observable
,它在操作开始时发出 true
,在操作结束时发出 false
.我想在操作进行时显示一条消息,但前提是开始时间超过两秒.有没有办法创建一个可以将消息绑定到的可观察对象?非常感谢任何帮助!
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!
推荐答案
如果你 switchMap(一个 flatMap,当第二个 item 从源发出时,对原始 observable 的订阅被取消订阅,订阅移动到下一个)你可以做这样的事情:
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(将 true 映射到 2 秒的可观察计时器,将 false 映射到空的可观察对象)
- .onNext 显示您的消息(next 不会为空的和一个快速响应会切断 2 秒计时器).
注意 switchMap 在 RxSwift 中是 'switchLatest'.
Note switchMap is 'switchLatest' in RxSwift.
可能变成这样:
booleanObservable
.map { inProgress -> Observable<Bool> in
if inProgress {
return Observable.just(true).delay(time: 2)
} else {
return Observable.just(false)
}
}
.switchLatest()
这篇关于如何使用 RX 应用宽限时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!