Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i convert setTimeout method to observable.timer?

Hear i am iterating array and i want to run this loop after every 2 sec.

 let Array = [1,2,3,4,5,6]  
      for (i = 0; i < Array.length; i++) {
          setTimeout((item)=>{
           //business logic
          console.log("item", item);
          }, 2000 * i, Array[i]);
    }

How can i convert this code in observable.timer method?

like image 407
nks Avatar asked Jan 22 '19 09:01

nks


People also ask

How do I stop observable timer?

call unsubscribe() on the Subscription object returned from the subscribe() call . use an operator.


2 Answers

This should work:

    let Array = [1,2,3,4,5,6]
rxjs.interval(2000)
.pipe(
    rxjs.operators.take(Array.length),
    rxjs.operators.map(i => Array[i])
).subscribe(value => console.log(value));
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.3.3/rxjs.umd.min.js"></script>

It automatically ends after Array.length items (take) and yields the items in subscribe (map) instead of their index.

RxJS v5 Version:

    let Array = [1,2,3,4,5,6]
Rx.Observable.interval(2000)
.take(Array.length)
.map(i => Array[i])
.subscribe(value => console.log(value));
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.12/Rx.min.js"></script>
like image 76
tkausl Avatar answered Oct 10 '22 10:10

tkausl


well done, there should be a es6 version with rxjs 6.x :

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

const array = [2, 3, 4, 5, 6];
interval(2000)
  .pipe(take(array.length))
  .pipe(map(i => array[i]))
  .subscribe(
    val => console.log(val)
  );
like image 29
zhimin Avatar answered Oct 10 '22 10:10

zhimin