RxJS 1 array item into sequence of single items - operator

前端 未结 5 585
一向
一向 2021-01-11 10:40

Given such observable

Rx.Observable.of([1,2,3,4,5])

which emits a single item (that is an array), what is the operator

相关标签:
5条回答
  • 2021-01-11 11:05

    mergeAll:

    Observable.of([4, 5, 6])
      .mergeAll()
      .subscribe(console.log);
    // output:
    // 4
    // 5
    // 6
    
    0 讨论(0)
  • 2021-01-11 11:10

    You can also use the flatMap operator (https://stackoverflow.com/a/32241743/3338239):

    Observable.of([1, 2, 3, 4])
      .flatMap(x => x)
      .subscribe(x => console.log(x));
    // output:
    // 1
    // 2
    // 3
    // 4
    
    0 讨论(0)
  • 2021-01-11 11:20

    I can't think of an existing operator to do that, but you can make one up :

    arrayEmitting$.concatMap(arrayValues => Rx.Observable.merge(arrayValues.map(Rx.Observable.of)))
    

    or the simpler

    arrayEmitting$.concatMap(Rx.Observable.of)
    

    or the shortest

    arrayEmitting$.concatMap(x => x)
    

    That is untested so let me know if that worked for you, and that uses Rxjs v4 API (specially the last one). This basically :

    • process each incoming array of values as one unit (meaning that the next incoming array will not interlap with the previous one - that is why I use concatMap)
    • the incoming array is transformed into an array of observables, which are merged : this ensures the emission of values separately and in sequence
    0 讨论(0)
  • 2021-01-11 11:20

    Dont understand why concatMap(x => x) or flatMap(x => x) works, it doesnt change anything. This should work (rxjs 6 or above):

    of([4,5,6]).pipe(mergeMap(from))
    
    0 讨论(0)
  • 2021-01-11 11:23

    You can use from now to convert an array into a sequence.

    https://www.learnrxjs.io/operators/creation/from.html

    from([4,5,6])

    0 讨论(0)
提交回复
热议问题