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?
Asked
Active
Viewed 1,186 times
0
-
2Can you provide some code what you've done? – shafayat hossain Oct 09 '20 at 03:34
3 Answers
1
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)
}

Yeldar Nurpeissov
- 1,786
- 14
- 19
0
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.

Virendra
- 115
- 2
- 10
0
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
}
)

rawhost
- 144
- 1
- 6