Lau
Lau

Reputation: 1834

RxJava 3 - PublishSubject emit data after subscribe

I want to listen on relay and after subscribe emit first item on the same relay. So naturally I wrote:

val relay = PublishSubject.create<Int>()

relay
    .doOnSubscribe { relay.onNext(1) }
    .subscribe {
        println("Test: $it")
    }

And unfortunately "Test: 1" was not printed.

After few tweaks I figured that it has to be on different thread, and this works:

relay
    .doOnSubscribe {
        Completable.fromAction { relay.onNext(1) }
            .subscribeOn(Schedulers.io())
            .subscribe()
    }
    .subscribe {
        println("Test: $it")
    }

It feels like a hack. Any idea why first version is not working? And any 'prettier' solution?

Upvotes: 1

Views: 194

Answers (0)

Related Questions