Why use Redux-Observable over Redux-Saga?

前端 未结 7 1196
太阳男子
太阳男子 2020-12-22 15:22

I have used Redux-Saga. Code written with it is easy to reason so far, except JS generator function is messing up my head from time to time. From my understanding, Redux-Obs

7条回答
  •  旧时难觅i
    2020-12-22 15:51

    I think there are things that you need to take in consideration.

    1. Complexity
    2. Coding Style
    3. Learning Curve
    4. Testability

    Lets say we want to fetch user from API

    // Redux-Saga
    
    import axios from 'axios' 
    
    function* watchSaga(){
      yield takeEvery('fetch_user', fetchUser) // waiting for action (fetch_user)
    }
    
    function* fetchUser(action){
        try {
            yield put({type:'fetch_user_ing'})
            const response = yield call(axios.get,'/api/users/1')
            yield put({type:'fetch_user_done',user:response.data})
      } catch (error) {
            yield put({type:'fetch_user_error',error})
      }
    }
    
    // Redux-Observable
    import axios from 'axios'
    
    const fetchUserEpic = action$ => 
        action$
            .ofType('fetch_user')
            .flatMap(()=>
              Observable.from(axios.get('/api/users/1')) // or use Observable.ajax
                .map(response=>({type:'fetch_user_done', user:response.data}))
                .catch(error => Observable.of({type:'fetch_user_error',error}))
                .startWith({type:'fetch_user_ing'})
            )
    

    Also, I have written this article in order compare the differences between Redux-saga and Redux-Observable in depth. Check out this link here or presentation.

提交回复
热议问题