Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS 1 array item into sequence of single items - operator

Given such observable

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

which emits a single item (that is an array), what is the operator that will transform this observable to a one that emits 5 single items (or whatever the array consists of)?

The example is on .of, but it would be the same for fetching arrays via promises, there might be many other examples. Don't suggest to replace of with from

like image 799
ducin Avatar asked Apr 07 '17 16:04

ducin


People also ask

What is concatMap in RxJS?

concatMap operator is basically a combination of two operators - concat and map. The map part lets you map a value from a source observable to an observable stream. Those streams are often referred to as inner streams.

What is flattening operator in RxJS?

Flattening operators come to our rescue when we have a nested subscription i.e subscribing to an observable within another subscription. This can be pretty annoying to track and debug. Its similar to “Callback hell” scenario where we have nested callbacks.

What is of () RxJS?

RxJS' of() is a creational operator that allows you to create an RxJS Observable from a sequence of values. According to the official docs: of() converts the arguments to an observable sequence. In Angular, you can use the of() operator to implement many use cases.

Which RxJS operators used for transforming or manipulating data?

Pipeable Operators and Creation Operators are the two kinds of operators in RxJS. The Pipeable Operators are methods that take an Observable as input and return another Observable. They can be piped to Observables using the syntax observableInstance. pipe(operator()) .


1 Answers

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
like image 104
user3743222 Avatar answered Sep 19 '22 17:09

user3743222