Balazs Banyai
Balazs Banyai

Reputation: 696

RxJava: Emit most recent item from upstream periodically

I'm looking for a solution that would emit the most recent item from the upstream periodically. ThrottleLatest is not exactly what I need, as I would like to emit the most recent item that was ever received from the upstream, not just in the last throttling interval.

Flowable.interval(3, TimeUnit.SECONDS)
    .operatorThatEmitsMostRecentItemFromUpstream(1, TimeUnit.SECONDS) 
    .subscribe { println(it) }

Desired output: 0, 0, 0, 1, 1, 1, 2, 2, 2, ...

Upvotes: 0

Views: 66

Answers (1)

akarnokd
akarnokd

Reputation: 70017

There is no standard operator for this but you can peek into a sequence, save the current item, and in the timer sequence, keep reading this saved item:

Flowable<T> source = ...
Flowable<Long> sampler = Flowable.interval(1, TimeUnit.SECONDS);

Flowable.defer(() -> {
    var item = new AtomicReference<T>();
    return source.doOnNext(item::set)
           .ignoreElements()
           .toFlowable()
           .mergeWith(
                sampler
                .filter(v -> item.get() != null)
                .map(v -> item.get())
           );
});

Upvotes: 1

Related Questions