I'm looking for a Subject (or something similar) that can:
- Could receive items and hold them in a queue or buffer if there are no subscribers
- Once we have a subscriber all items are consumed and never emitted again
- I can subscribe/unsubscribe to/from Subject
BehaviorSubject almost would do the job, but it retains last observed item.
UPDATE
Based on accepted answer I worked out similar solution for single observed item. Also added unsubscription part to avoid memory leaks.
class LastEventObservable private constructor(
private val onSubscribe: OnSubscribe<Any>,
private val state: State
) : Observable<Any>(onSubscribe) {
fun emit(value: Any) {
if (state.subscriber.hasObservers()) {
state.subscriber.onNext(value)
} else {
state.lastItem = value
}
}
companion object {
fun create(): LastEventObservable {
val state = State()
val onSubscribe = OnSubscribe<Any> { subscriber ->
just(state.lastItem)
.filter { it != null }
.doOnNext { subscriber.onNext(it) }
.doOnCompleted { state.lastItem = null }
.subscribe()
val subscription = state.subscriber.subscribe(subscriber)
subscriber.add(Subscriptions.create { subscription.unsubscribe() })
}
return LastEventObservable(onSubscribe, state)
}
}
private class State {
var lastItem: Any? = null
val subscriber = PublishSubject.create<Any>()
}
}