Anirudha Mahale
Anirudha Mahale

Reputation: 2596

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.

Upvotes: 7

Views: 16611

Answers (2)

Lew Winczynski
Lew Winczynski

Reputation: 1239

If you want to put a delay for your Observable to emit a value, you can simply do something like this:

Observable.just(()).delay(.seconds(2), scheduler: MainScheduler.instance)

Upvotes: 33

Mateusz Chechliński
Mateusz Chechliński

Reputation: 823

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.

Upvotes: 8

Related Questions