https://kotlinlang.org logo
#rx
Title
# rx
a

arekolek

09/19/2019, 11:16 AM
Something like this?
Copy code
val isRead = AtomicBoolean(false)
val testObservable = Maybe.fromCallable { true.takeUnless { isRead.getAndSet(true) } }.toObservable()
f

filipradon

09/19/2019, 3:23 PM
My colleage finally come up with such solution which is basically quite similar but encapsulating this flag inside a class
Copy code
class ColdObservableSingleSubscriberProxy<T>(val value: T) {
    private var hasBeenSubscribed = false

    fun getObservable(): Observable<T> =
        if (hasBeenSubscribed) {
            Observable.never<T>()
        } else {
            hasBeenSubscribed = true
            Observable.just(value)
        }
}
😎 1
a

arekolek

09/19/2019, 3:43 PM
One problem with it is that the
if
is evaluated at assembly, not at subscription. So if you call
getObservable()
once, all its subscribers will still get the value
👍 1
image.png
r

reline

09/19/2019, 3:49 PM
how’s this?
Copy code
fun <T> Observable<T>.toColdSingleSubscribeable(): Observable<T> {
    return ColdObservableSingleSubscriberProxy(this)
}

class ColdObservableSingleSubscriberProxy<T>(private val observable: Observable<T>) : Observable<T>() {

    private val hasBeenSubscribed = AtomicBoolean(false)

    override fun subscribeActual(observer: Observer<in T>) {
        if (hasBeenSubscribed.compareAndSet(false, true)) {
            observable.subscribe(observer)
        } else {
            never<T>().subscribe(observer)
        }
    }

}
✔️ 1
this would always return
false
for
isDisposed
however, so use
empty()
instead of
never()
if you want it
isDisposed
to return true immediately after subscribing.