Search code examples
delayrx-swift

How to put delay in RxSwift?


I have an Observable to perform some task and I want it to give me result after 5 seconds but it gives me before that and sometimes after 5 seconds depending upon the complexity.

For example:

If my code completed the task in 2 seconds and is about to emit the computed value. I want it to wait for more 3 remaining seconds and then emit the computed value.

How can I achieve this? I have heard about debounce and throttle.


Solution

  • You can use Observable.timer along with Observable.zip.

    Something like:

    Observable<MyType>.zip(
        myObservable, 
        Observable<Int>.timer(RxTimeInterval.seconds(5), scheduler: MainScheduler.instance),
        resultSelector: { myItem, _ in return myItem }
    )
    

    Result selector is to ignore value produced by timer.