Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert array to sequence of items with flatMap

In RxJS I want to convert an array that I have at some point into a sequence of items that are in the array. I found two ways to do it: Option 1 & 2, which I guess, do the same thing:

const obj = { array: [1, 2, 3, 4, 5] };

const observable = Observable.of(obj);

// Option 1
observable.flatMap(x => {
  return Observable.from(x.array);
}).subscribe(console.log);

// Option 2
observable.flatMap(x => x.array).subscribe(console.log);

// Option 3 ?

Are there nicer / better ways that express what I'm doing , I mean without flatMap operator?

like image 447
dragonfly Avatar asked Jul 01 '17 14:07

dragonfly


1 Answers

I think you've pretty much reached the shortest possible way. The only improvement I might suggest is avoid using callback functions at all:

const obj = { array: [1, 2, 3, 4, 5] };
const observable = Observable.of(obj);

observable
  .pluck('array')
  .concatAll() // or mergeAll()
  .subscribe(console.log);

See live demo: https://jsbin.com/zosonil/edit?js,console

like image 98
martin Avatar answered Oct 12 '22 23:10

martin