Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
620 views
in Technique[技术] by (71.8m points)

reactive programming - Rxjs - How can I extract multiple values inside an array and feed them back to the observable stream synchronously

I have created a Rx.Observable from a stream of events:

Rx.Observable.fromEvent(recognizeStream, 'data')

In which every data event looks like this:

{ error: null, alternatives: [result1, result2, result3] }

I want to pluck every value inside the array of alternatives and merge those into the stream. What operators do I have to look at?

As far as I know the flatMap and concatMap could do the job but I don't get the idea from their example.

Can somebody explain which operator i should use and provide me with an example?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The family of xxxMap() operators all deal with higher-order Observables. Which means they allow you to create Observables inside the main Observable and inline the resulting values into the primary stream. So you could read the type signature as Observable<Observable<T>> => Observable<T>

Given a stream which every emission x is an Observable containing 4 value emissions:

input:  --x----------x 
flatMap   a-a-a-a-|  b-b-b-b-|
result: --a-a-a-a----b-b-b-b-|

Typecasting xxxMap(myFnc) return values

The xxxMap() operators all work with results of type Observable, Promise or Array. Depending on what you put into it will get converted to Observable if needed.

Rx.Observable.of('')
  .flatMap(() => [1,2,3,4])
  .subscribe(val => console.log('array value: ' + val));

Rx.Observable.of('')
  .flatMap(() => Promise.resolve(1))
  .subscribe(val => console.log('promise value: ' + val));

Rx.Observable.of('')
  .flatMap(() => Promise.resolve([1,2,3,4]))
  .subscribe(val => console.log('promise array value: ' + val));

Rx.Observable.of('')
  .flatMap(() => Rx.Observable.from([1,2,3,4]))
  .subscribe(val => console.log('Observable value: ' + val));
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.0.3/Rx.js"></script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...