2017-11-07 8 views
0

は、だから、私はこのサガを選択し、プットがテイクをブロックしているので、SELECT_THING行動を取って欠場する可能性があることが言われているので、このサガに並行性の問題はありますか?

function* watchSelectThing() { 
    let currentThing = yield select(getSelectedThing); 
    while (true) { 
    yield take(types.SELECT_THING); 
    const nextSelectedThing = yield select(getSelectedThing); 
    if (currentThing !== nextSelectedThing) { 
     currentThing = nextSelectedThing; 
     yield put(actions.updateSomeOtherThing({})); 
     yield put(actions.fetchOtherStuff()); 
    } 
    } 
} 

のような武勇伝を持っています。たとえば、2つのputの間にSELECT_THINGアクションが発生したとします。私はそれが妥当と思われると思います。

もしそうなら、まだcurrentThingの必要な状態を維持できる一方で、それをnextSelectedThingと比較できるようにする方法がありますか?私の脳は今見ていない。

答えて

1

takeは、次のアクションが起こるのを待っており、過去のアクションのバッファを持っていません。これを解決するにはtakeLatestを使用できます。

let currentThing 

function* saga() { 
    currentThing = yield select(getSelectedThing); 
    yield takeLatest(types.SELECT_THING, selectThingFlow) 
} 

function* selectThingFlow() { 
    const nextSelectedThing = yield select(getSelectedThing); 

    if (currentThing !== nextSelectedThing) { 
    currentThing = nextSelectedThing; 
    yield put(actions.updateSomeOtherThing({})); 
    yield put(actions.fetchOtherStuff()); 
    } 
} 

takeLatesttakeEveryの違いはredux-saga実行フローを継続またはキャンセルする方法です。 SELECT_THINGアクションが発生するとすぐにtakeLatestselectThingFlowがキャンセルされます。フローがどこにあっても(例えばupdateSomeOtherThing)、次のアクションfetchOtherStuffはもう呼び出されませんでしたが、フローはgetSelectedThingで再開します。

takeEveryただし、getSelectedThingで始まる別のselectThingFlowも開始しますが、前のフローの実行は取り消されません。

+0

私はそれについて考えていました。しかし、 'yield select(getSelectedThing)'が同じ問題を引き起こすかどうかは疑問です。 –

+1

はい、あなたは正しいです。私はそれに応じて答えを変えた。お役に立てれば! – Alex

関連する問題