Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS emit array items over time?

Tags:

rxjs

I'm trying to emit simple array values one after another with 500ms in between:

var a = Rx.Observable.from([1,2,3]);
a.interval(500).subscribe(function(b) { console.log(b); });

However, this throws an exception:

Uncaught TypeError: a.interval is not a function.
like image 709
Bryce Avatar asked May 02 '15 06:05

Bryce


3 Answers

Three ways to do it, with RxJS version 6 :

1. Using concatMap

import { from, of, pipe } from 'rxjs';
import { concatMap, delay } from 'rxjs/operators';

const array = [1, 2, 3, 4, 5];

from(array)
 .pipe(
   concatMap(val => of(val).pipe(delay(1000))),
 )
 .subscribe(console.log);

2. Using zip and interval

import { from, pipe, interval } from 'rxjs';
import { delay, zip} from 'rxjs/operators';

const array = [1, 2, 3, 4, 5];

from(array)
 .pipe(
   zip(interval(1000), (a, b) => a),
 )
 .subscribe(console.log);

3. Using interval as source

import { interval, pipe } from 'rxjs';
import { map, take } from 'rxjs/operators';

const array = [1, 2, 3, 4, 5];

interval(1000)
.pipe(
  take(array.length),
  map(i => array[i])
)
.subscribe(console.log);
like image 85
Michael P. Bazos Avatar answered Oct 31 '22 03:10

Michael P. Bazos


As already pointed out by xgrommx, interval is not an instance member of an observable but rather a static member of Rx.Observable.

Rx.Observable.fromArray([1,2,3]).zip(
  Rx.Observable.interval(500), function(a, b) { return a; })
.subscribe(
  function(x) { document.write(x + '<br \>'); },  
  null,  
  function() { document.write("complete"); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/2.5.2/rx.all.min.js"></script>
like image 39
Oliver Weichhold Avatar answered Oct 31 '22 03:10

Oliver Weichhold


This is how I would do it:

var fruits = ['apple', 'orange', 'banana', 'apple'];
var observable = Rx.Observable.interval(1000).take(fruits.length).map(t => fruits[t]);
observable.subscribe(t => {
  console.log(t);
  document.body.appendChild(document.createTextNode(t + ', '));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/2.5.2/rx.all.min.js"></script>
like image 10
pixelbits Avatar answered Oct 31 '22 05:10

pixelbits