'Can RxJava be used to send messages only to the most recent subscriber?

I've been given a requirement that when there are multiple observers, only the most recent subscription should receive messages. I'll illustrate with sloppy code examples.

val fooDisposable = mostRecentSubscriberObservable.subscribe(this::foo)

Any time mostRecentSubscriberObservable emits an item, foo() is called.

Now this runs:

val barDisposable = mostRecentSubscriberObservable.subscribe(this::bar)

Now whenever an item is emitted, bar() is called, because barDisposable is the most recent subscriber. foo() is NOT called.

Now this runs:

barDisposable.dispose()

Now whenever an item is emitted, foo() is called. Now that barDisposable is gone, fooDisposable is the most recent subscriber, and receives the item.

Short of creating a custom Subject class (which seems rather complex), is there a way to do this - any existing Subject or combination of operators which would accomplish it? I can't seem to find anything like that.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source