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:
mainField must be transmitted first, response object will be supplied with reference ID, that subFields will usesubFields must be transmitted as single, and when response will arrive, another can be requestedConceptually 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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With