Reactive Programming: Periodically emitting Events with RxJava2

Reactive Programming is an asynchronous programming language paradigm, which makes it astonishingly easy to work with Data Streams. Once you start with Reactive Programming you are going to see it everywhere, everything is going to look like a data stream.

I started to work with Reactive Extensions in .NET some years ago and by now almost every other programming language has additional libraries for Reactive Programming like RxJava, RxJS or RxCpp. Like every other technology reactive programming doesn't come without its pitfalls and it often has a steep learning curve, but learning it is really worth the time.

Yesterday I needed to emit events periodically in a synchronous fashion in Java, and it is easy with RxJava. I think sharing the solution is a nice showcase for Reactive Programming.

RxJava Implementation

I needed a simple function, which takes a List and emits its values in a specified interval. The implementation should be synchronous, so I subscribed to the Observable in a blocking fashion.

public <TEventType> void emitEvents(Iterable<TEventType> events, Duration duration) {
    Observable.zip(
            Observable.fromIterable(events),
            Observable.interval(duration.toMillis(), TimeUnit.MILLISECONDS),
            (obs, timer) -> obs
    ).blockingSubscribe(new Consumer<TEventType>() {
        @Override
        public void accept(TEventType event) throws Exception {
            // Do something with the event...
        }
    });
}

How to contribute

One of the easiest ways to contribute is to participate in discussions. You can also contribute by submitting pull requests.

General feedback and discussions?

Do you have questions or feedback on this article? Please create an issue on the GitHub issue tracker.

Something is wrong or missing?

There may be something wrong or missing in this article. If you want to help fixing it, then please make a Pull Request to this file on GitHub.