2017-12-21 4 views
2

conditionフィールドに返される値によっては、repeatに約束しています。 vが未定義であり、ランダムTypeError: Cannot read property 'condition' of undefined放射値に応じてRxJSが繰り返されます

をスローにconsole.logのO/Pは{ Items: [ 1, 2, 3, 4, 5 ], condition: 5, time: 1513827310333 }

JSFiddle

const source = Rx.Observable.fromPromise(
    Promise.resolve({ 
    Items: [1, 2, 3, 4, 5], 
    condition: Math.floor(Math.random() * 10), 
    time: +new Date() 
    }) 
); 

source 
    .map(val => val) 
    .repeatWhen(val => { 
    return val.map(v => { // v is undefined 
     if (v.condition > 0) { 
     return Rx.Observable.of(v); 
     } else { 
     return Rx.Observable.empty(); 
     } 
    }); 
    }) 
    .finally(() => { 
    done(); 
    }) 
    .subscribe(val => console.log(val)); 

答えて

0

で、外部フラグを操作ガットANため、次のブロックが機能しませんソースは繰り返しごとに評価されます。

const source = Rx.Observable.defer(() => 
 
    Promise.resolve({ 
 
    Items: [1, 2, 3, 4, 5], 
 
    condition: Math.floor(Math.random() * 10), 
 
    time: +new Date() 
 
    }) 
 
); 
 

 
let condition = false; 
 

 
source 
 
    .repeatWhen(notifications => { 
 
    return notifications 
 
     .scan(() => { 
 
     return condition; 
 
     }, false) 
 
     .delay(100) 
 
     .takeWhile(() => { 
 
     return condition; 
 
     }); 
 
    }) 
 
    .do(x => (condition = x.condition !== 0)) 
 
    .finally(console.log("done")) 
 
    .subscribe(console.log);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.5/Rx.min.js"></script>

+1

またごとのサブスクリプションの状態に外部の状態を変更するには、 'defer'を使用することができます:' constの繰り返し= Rx.Observable.defer(()=> {状態を聞かせて、ソース。 .repeatWhen(/ * etc. * /);}); '外部状態は避けるのが最善です。 – cartant

+0

@cartant素晴らしいアイデア。これをテストしてお知らせします。 – nilobarp

+0

前のコメントのコードで 'source'の前に' return'があったはずです。次に、 'finally'と' subscribe'を 'repeats'で観測します。 – cartant

関連する問題