简体   繁体   中英

Return an observable from setTimeout (Rxjs)

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);
  }
}

Something like this (you can't return anything from setTimeout() ):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM