Tomas
Tomas

Reputation: 3446

RxJS toArray() equivalent

consider following scenario: Array of values shall be processed one after another and after processing once again single array value shall be returned. Following code will do the trick:

Observable.of([1, 2, 3, 4]) /* Base array */
.concatMap<number[], number[]>(valArr => { /* Inner stream to process array */
  return Observable.from(valArr) /* breake apart array into values */
  .map<number, number>((num, idx) => {
    return valArr[idx] + 1; 
  })
  .toArray()
})
.subscribe(arr => {
  console.log(arr)
})

I.e. will decompose stream into single element stream, do some operations on values and toArray() will merge it back to array response. Whole further processing is stopped until internal concatMap processing single element is not completed.

The question is, how to achieve same behavior without toArray() usage?

Upvotes: 1

Views: 2148

Answers (3)

Fabricio
Fabricio

Reputation: 7935

Observable.from([1, 2, 3, 4])
          .reduce((acc, curr) => [...acc, curr + 1], [])

// result: [2, 3, 4, 5]

Upvotes: 0

Tomas
Tomas

Reputation: 3446

We just come up with following workarounds:

Using concat:

Observable.of([1, 2, 3, 4]) /* Base array */
.concatMap<number[], number[]>(valArr => { /* Inner stream to process array */


  return Observable.from(valArr) /* breake apart array into values */
  .map<number, number>((num, idx) => {
    return valArr[idx] + 1; 
  })
  .concat(Observable.from(valArr))
})
.subscribe(arr => {
  console.log(arr)
})

Using last:

Observable.of([1, 2, 3, 4]) /* Base array */
.concatMap<number[], number[]>(valArr => { /* Inner stream to process array */

  return Observable.from(valArr) /* breake apart array into values */
  .map<number, number>((num, idx) => {
    return valArr[idx] + 1; 
  })
  .last()
  .map(v => {
    return Observable.from(valArr)
  })
})
.subscribe(arr => {
  console.log(arr)
})

Upvotes: 0

Mark van Straten
Mark van Straten

Reputation: 9425

You can simplify your code by using Observable.from() on your baseArray and skipping the concatMap//inner observable logic. If you want to end up with an array your best option is indeed to use .toArray() at the end:

Observable.from([])
  .map((val) => 1 + val)
  .toArray()

Upvotes: 1

Related Questions