RxSwift: How to stream values with dynamic delay

Imagine such case – you have list of messages, each one with timestamp. And you want to show them in the same way they arrived, with same timings. How to achieve this with RxSwift?

Lets start with test structure, which in our example will hold only basic data, but feel free to modify it as you want:

Note “delay” attribute, which holds value after each message should be shown. Then you can create array of messages:

Of course in real world, this array will be fetched from database or JSON. Then next step is stream each one this way:

What happens here? First we are declaring our “delay” variable, which will cumulate delay for each next message. Note that this is not perfect, as with big arrays, parsing flatMap can take some time, and messages can be delayed because of this. But usually it is enough. Next comes the most important step – for each incoming element, we are returning Observable type for element itself, but with delayed subscription. This will cause .subscribe() to be executed after given delay.

The final step is to push each element from array, to our PublishSubject. In given case, your output should look like this:

As you can see, we started output at 18:33:34.110, then next element is delayed by 0.3 sec, and displayed at 18:33:34.410, next is delayed by 1.2 sec and displayed at 18:33:35.610, and so on. Each one, exactly in same order we put them into subject. And don’t forget to add :

as your view controller property.

Leave a Reply