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?
call unsubscribe() on the Subscription object returned from the subscribe() call . use an operator.
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>
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)
  );
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With