RXKotlin - How to receive single event

1.3k Views Asked by At

I am getting callback event from an object twice sometime thrice but I need to collect only one object that will be the latest one. Is it possible with RX kotlin?

3

There are 3 best solutions below

0
On

If your observable is emitting multiple times but you only need the latest one then you can use Observable.blockingLast() to get that item and ignore the rest.

Similarly, you can user Observable.blockingFirst() to only get the first result.

Note that both of these will block the current thread.

0
On

If contents are different:

Observable.create<String> {
    it.onNext("One")
    it.onNext("Two")
    it.onComplete()
}
.lastOrError()
.subscribe { data, error ->
    Log.d("Log", data)
}

If contents are same:

Observable.create<String> {
    it.onNext("One")
    it.onNext("One")
    it.onComplete()
}
.distinctUntilChanged()
.subscribe {
    Log.d("Log", it)
}

Or combine them together:

Observable.create<String> {
    it.onNext("One")
    it.onNext("Two")
    it.onNext("Two")
    it.onNext("Two")
    it.onComplete()
}
.distinctUntilChanged()
.lastOrError()
.subscribe { data, error ->
    Log.d("Log", data)
}
0
On

Single behaves similarly to Observable except that it can only emit either a single successful value or an error (there is no "onComplete" notification as there is for an Observable).

        Single.create<String> {
            it.onSuccess("one")
            it.onSuccess("two")
            it.onSuccess("three")
        }.subscribe(
            {
//            ON Succuess
            },
            {
// on error
            }
        )