1

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())
                );
Necronet
  • 6,704
  • 9
  • 49
  • 89
  • 1
    Do you need the results of both? If yes, this would be not a great idea to combine both to one stream. A stream should only be for one type or for one supertype: SectionEntity, ItemEntity inherit from 'Entity'. The observable would be of type 'Entity' and you would check with instance of what type it is and dependend on the type you could invoke different actions. – Sergej Isbrecht Apr 25 '17 at 23:10

1 Answers1

1

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(...)
Maksim Ostrovidov
  • 10,720
  • 8
  • 42
  • 57