0

I have the following code:

 model.getCategories()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<List<Category>>()
                {
                    @Override
                    public void call(final List<Category> categories)
                    {
                        model.getUnits()
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new Action1<List<Unit>>()
                                {
                                    @Override
                                    public void call(List<Unit> units)
                                    {
                                        view.showAddProductDialog(units, categories);
                                    }
                                });
                    }
                });

I have this ugly nesting. How can I fix it. I tried something like this:

Single.concat(model.getCategories(), model.getUnits())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<List<? extends Object>>()
                {
                    @Override
                    public void call(List<? extends Object> objects)
                    {
                        // do something
                    }
                });

But the problem is that I cannot determinate whether it is List<Category> or List<Unit> comes.

Is there a way to use concat and detect what kind of stream comes (List<Category> or List<Unit> or something else) ?

Also I need to detect that all observers are completed to perform another action.

Thanks in advice.

Andrey
  • 83
  • 6

1 Answers1

2

Use Single.zip():

Single.zip(
    getCategories().subscribeOn(Schedulers.io()),
    getUnits().subscribeOn(Schedulers.io()),
    (a, b) -> Pair.of(a, b)
)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
    pair -> view.showAddProductDialog(pair.first, pair.second),
    error -> showError(error.toString())
)

where Pair can be any tuple implementation, i.e., this.

akarnokd
  • 69,132
  • 14
  • 157
  • 192
  • I see, it should work for this sample, but what if it would have more nested actions, not only 2. – Andrey Aug 18 '17 at 12:13
  • 1
    Protip: look at the [javadoc](http://reactivex.io/RxJava/2.x/javadoc/io/reactivex/Single.html#zip(io.reactivex.SingleSource,%20io.reactivex.SingleSource,%20io.reactivex.SingleSource,%20io.reactivex.functions.Function3)) and/or what method overloads pop up in content assist of your IDE when typing `Single.`. – akarnokd Aug 18 '17 at 12:22