Sequence of API calls through observable

283 Views Asked by At

Hi I'm trying to get two observable to be called in sequence, one after the other. I tried using merge but it does not respect order so I went and used concat instead, the main problem is that these two Observable emit different types. From what I've been seeing zip could be an option to merge two different observable but haven't wrapped my head around it.

So the concrete question si, how can one have sequential API being call after the other. Currently this is my implementation

 Observable<SectionEntity> sectionEntitySync = DbProvider.contentResolver(this)
                .createQuery(KitchContract.Category.CONTENT_URI, null, KitchContract.DELETED + "=?",
                        new String[] { KitchContract.NO }, KitchContract.Category.Columns.POSITION + " ASC", true)
                .mapToList(SectionEntity::new)
                .flatMap(Observable::from)
                .flatMap(sectionEntity -> getApi().create(sectionEntity)
                        .subscribeOn(Schedulers.newThread())
                        .observeOn(AndroidSchedulers.mainThread()));

        Observable<ItemEntity> itemEntitySync = DbProvider.contentResolver(this)
                .createQuery(KitchContract.Item.CONTENT_URI, null, null, null,null, false)
                .mapToList(ItemEntity::new)
                .flatMap(Observable::from)
                .flatMap(itemEntity ->
                    getApi().create(itemEntity)
                            .subscribeOn(Schedulers.newThread())
                            .observeOn(AndroidSchedulers.mainThread())
                );
1

There are 1 best solutions below

0
Maksim Ostrovidov On

As I get it right, your second stream doesn't rely on results of the first one. So you could just wait for the first stream to complete with toList operator and then launch the second stream using flatMap:

sectionEntitySync
    .toList() //collect results. This operator also waits for upstream's onComplete
    .flatMapObservable(list -> itemEntitySync) //launch the second observable
    .subscribe(...)