Reputation: 521
I'm trying to do calculating one by one, asynchronously.
fun method1(): Int{
return 2+2
}
fun method2(value: Int): Int{
return value * 2
}
fun method3(value: Int): Int{
return value * 3
}
Now I want method 2 work after method 1 and take result from her. Also method 3 work after method 2 and take result from her. Is it possible to do that with rxkotlin and make it in one stream ?
Upvotes: 0
Views: 401
Reputation: 619
This can be done using flatMap
as follows :
fun performAsyncCalculation(): Observable<Int> {
return method1()
.flatMap { result1 -> method2(result1) }
.flatMap { result2 -> method3(result2) }
}
where the methods are :
fun method1(): Observable<Int> {
return Observable.create { emitter ->
// perform calculation to produce requiredInt1
emitter.onNext(requiredInt1)
emitter.onComplete()
}
fun method2(requiredInt1: Int): Observable<Int> {
return Observable.create { emitter ->
// perform calculation to produce requiredInt2
emitter.onNext(requiredInt2)
emitter.onComplete()
}
fun method3(requiredInt2: Int): Observable<Int> {
return Observable.create { emitter ->
// perform calculation to produce requiredInt3
emitter.onNext(requiredInt3)
emitter.onComplete()
}
Upvotes: 1
Reputation: 1838
If you want to chain that methods invocation you can do as presented below:
fun chain(): Single<Int> {
return Single.just(method1())
.map { result1 -> method2(result1) }
.map { result2 -> method3(result2) }
}
However, if operations in method1
, method2
or method3
are asynchronous I would suggest to wrap them in Single
.
For reference map
vs flatMap
take a look on:
https://medium.com/mindorks/rxjava-operator-map-vs-flatmap-427c09678784
Upvotes: 1