Sequential linking of sequences
What is the best practice to chain 5-6 single observables that are executed sequentially? For example, I have Single1-> Single2-> ... → Single6.
Single2 depends on the result of Single1. Single3 depends on the result of Single2, etc.
I used nested flatMap
code, but the code is really long and the readability is really low.
What's the best guideline for this case?
+3
source to share
1 answer
You don't need to nest the calls flatMap
, you can just chain them and get a clear chaining of the observable flow:
single1
.flatMap(new Func1<Item1, Single<Item2>>() {
@Override
public Single<Item2> call(Item1 obj) {
return getSingle2(obj);
}
})
.flatMap(new Func1<Item2, Single<Item3>>() {
@Override
public Single<Item3> call(Item2 obj) {
return getSingle3(obj);
}
})
.flatMap(new Func1<Item3, Single<Item4>>() {
@Override
public Single<Item4> call(Item3 obj) {
return getSingle4(obj);
}
})
.flatMap(new Func1<Item4, Single<Item5>>() {
@Override
public Single<Item5> call(Item4 obj) {
return getSingle5(obj);
}
})
.flatMap(new Func1<Item5, Single<Item6>>() {
@Override
public Single<Item6> call(Item5 obj) {
return getSingle6(obj);
}
});
and with a lambda it can get really neat:
single1
.flatMap(this::getSingle2)
.flatMap(this::getSingle3)
.flatMap(this::getSingle4)
.flatMap(this::getSingle5)
.flatMap(this::getSingle6);
0
source to share