Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I apply a grace time using RX?

Tags:

swift

rx-swift

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!

like image 990
Paul Avatar asked Oct 13 '17 11:10

Paul


1 Answers

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()
like image 92
Cargowire Avatar answered Oct 12 '22 23:10

Cargowire