3

What is the best practice of chaining 5-6 Single observables that are being executing sequentially? For example I have Single1->Single2-> ... ->Single6.

Single2 depends on Single1's result. Single3 depends on Single2 result, etc.

I have been using nested flatMap but the code gets really long and readability is really low.

What's the best guideline for this case?

yosriz
  • 10,147
  • 2
  • 24
  • 38
codereviewanskquestions
  • 13,460
  • 29
  • 98
  • 167

1 Answers1

0

You don't need to nest the flatMap calls, you can simply chain them and get clear chain of Observable stream:

 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 lambda it can get really neat:

single1
    .flatMap(this::getSingle2)
    .flatMap(this::getSingle3)
    .flatMap(this::getSingle4)
    .flatMap(this::getSingle5)
    .flatMap(this::getSingle6);
yosriz
  • 10,147
  • 2
  • 24
  • 38