Observable.just(1)
.flatMap(object : Function<Int, Observable<Int>> {
override fun apply(integer: Int): Observable<Int> {
return Observable.just(integer * 10)
}
})
.flatMap(object : Function<Int, Observable<Int>> {
override fun apply(integer: Int): Observable<Int> {
return Observable.just(integer * 20)
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : Observer<Int> {
override fun onComplete() {
}
override fun onSubscribe(d: Disposable) {
}
override fun onNext(t: Int) {
Log.d("result", "" + t)
}
override fun onError(e: Throwable) {
e.printStackTrace()
}
})
FlatMap transforms the items emitted by an Observable into Observables. So, the main difference between Map and FlatMap is that FlatMap mapper returns an observable itself, so it is used to map over asynchronous operations. Very important: FlatMap is used to map over asynchronous operations.
Coming to RxJava, RxJava streams are prone to leaks, where a stream continues to process items even when you no longer care. Kotlin coroutines use structured concurrency, which makes it much easier to manage the lifecycle of all your concurrent code.
RxJava can be used even when using the Kotlin language for app development.
A Disposable is a stream or a link between an Observable and an Observer . A quick check of the documentation shows that it has two main methods, dispose() and isDisposed() .
This should do.
Observable.just(1)
.flatMap {
return@flatMap Observable.just(it*10)
}.flatMap {
return@flatMap Observable.just(it*20)
}.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
.subscribe({
//OnNext
Log.d("result", "" + it)
},{
it.printStackTrace()
//on error
},{
//on complete
})
actually, return@flatMap
is not needed, so below works as well. Also, if you don't need all methods for a subscriber actually implemented, there's an overload with just onNext
and onError
. IDE's hints are of great help in here - when typing in a method, press Ctrl+P and it will show you available overloads. The keyboard shortcut is essentially "show me arguments".
Observable.just(1)
.flatMap { Observable.just(it * 10) }
.flatMap { Observable.just(it * 20) }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ Log.d("result", "" + it) },
{ it.printStackTrace() }
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With