简体   繁体   中英

Pipe an observable to update list of items with result from api

I have an observable which pumps a list of items. I need to pipe the observable so that each of the items would do an api call, update itself with the result from the api call and finally provide an updated list of items from the observable.

  • Consider an array like below
    [{id: 1, name: 'a'}, {id: 2, name: 'b'}, {id: 3, name: 'c'}]

  • Each item needs to do an api call which returns if its a 'new' or 'old' item
    GET /api/type/:id returns new / old

  • Update the item to take the api result value on a new type property

  • Return the updated list
    [{id: 1, name: 'a', type: 'new'}, {id: 2, name: 'b', type: 'old'}, {id: 3, name: 'c', type: 'new'}]

What kind of rxjs operators can i use to do this?

If you're ok with doing this sequentially you could try something like this

const items$ = from([{id: 1, name: 'a'}, {id: 2, name: 'b'}, {id: 3, name: 'c'}])

const request = async (data) => {
  // data here would be any single object in your array
  // and `doHttpRequest` is any function that returns the type
  // given the original object
  const type = await doHttpRequest(data)
  return {
    ...data,
    type
  }
}

const results$ = items$.pipe(
  // flatMap being used here since we're not returning
  // a synchronous value from request
  flatMap(request),
  toArray()
);

// somewhere else in your code
results$.subscribe(value => console.log(value));

If you omit the toArray part you could keep your observable as a stream of objects instead of a single array completing at the end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM