Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS sequential operations

I'm using RxJS to communicate with Database and I'm trying to send complex composite object. Our API let us to inject one element at time (i.e. POST will not handle array in body) Consider following object, where mainField & subFields will be separate tables entities in DB:

OBJ = {
      'mainField': 'Main content'
      'subFields': [ 'obj1','obj2','obj3' ]
    }

The requirements are:

  1. mainField must be transmitted first, response object will be supplied with reference ID, that subFields will use
  2. Each element of subFields must be transmitted as single, and when response will arrive, another can be requested

Conceptually procedure for me looks something like this (send function is a simplification that accepts anything and return observable of this type):

send(OBJ.mainField) /* This will return Observable of mainField */
.flatMap(res => {
   OBJ.subFields.forEach(sub => {
     sub.id = res.id
   })
   Obervable.of(OBJ.subFields)
})
.flatMap(subField => {
  send(subField )
})

I believe there is a better way to do this (i.e. brake apart array, emit series of observables and wait untill they complete in order, then move on). I'd be grateful for any suggestions

like image 363
Tomas Avatar asked Feb 15 '26 12:02

Tomas


1 Answers

You can use concat that makes sure the Observables are subscribed in order only after the previous one completed.

Observable.of(OBJ) // or whatever...
  .concatMap(obj => {
    const mainField$ = send(obj.mainField);
    // the `concat()` subscribes to each Observable in order
    const subFields$ = Observable.concat(obj.subFields.map(field => send(obj.mainField)));

    // start processing `subFields$` after `mainField$` completed
    return mainField$.concat(subFields$);
  })
  .subscribe(() => console.log('All done'));

If you're not using Observable.of(OBJ) in you use-case you can use send(obj.mainField) instead like you did.

like image 75
martin Avatar answered Feb 17 '26 01:02

martin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!