2017-04-20 121 views
1

如何從setTimeout返回可觀察值?從setTimeout(Rxjs)返回可觀察值

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

複製和粘貼例如:

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

給人的感覺並不權使用具有可觀察性的'setTimeout'。 'delay'運算符怎麼樣? – Maxime

回答

3

像這樣的東西(你不能返回從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); 
    } 
} 
+0

@Ced我知道,我以爲你已經知道這一點:) – martin