Home:ALL Converter>Return an observable from setTimeout (Rxjs)

Return an observable from setTimeout (Rxjs)

Ask Time:2017-04-21T02:41:38         Author:Ced

Json Formatter

How do you return an observable from setTimeout ?

send(action):Observable<any>{
  if(this.readyState === 0 ){
    setTimeout(() => this.send(action), this.timeout);
  }
  else{
    // observable is an Rxjs observable....
    return this.observable$.take(1);
  }
}

A copy and paste example :

let observable$ = Rx.Observable.fromArray([1, 2, 3, 4, 5]);
timeout = 40;
// if you switch this to 1 it works..
readyState = 0;
setTimeout( () => readyState = 1, 120);

send().subscribe(c => console.log(c));

function send(action){
  if(readyState === 0 ){
    setTimeout(() => send(action), timeout);
  }
  else{
    return observable$.take(1);
  }
}

Author:Ced,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/43527457/return-an-observable-from-settimeout-rxjs
yy