How to watch object changes with rxjs 5

后端 未结 3 2217
孤街浪徒
孤街浪徒 2021-02-08 23:41

I would like to watch over an object, so all the subscribers will be informed for any changes of it.

I saw it already been asked before, yet the answer is irrelevant si

3条回答
  •  花落未央
    2021-02-08 23:53

    I would suggest using something similar to redux approach, when changes to the object can be made in predefined way:

    function factory(reducerByType, initialState) {
      const action$ = new Rx.Subject();
      const state$ = action$
        .startWith(initialState)
        .scan((state, action) => {
          if (reducerByType.hasOwnProperty(action.type)) {
            return reducerByType[action.type](state, action);
          }
          
          return state;
        })
        .distinctUntilChanged();
      
      
      return {
        action$,
        state$,
        dispatch: action => action$.next(action)
      }
    }
    
    const {state$, dispatch} = factory({
      ADD: (state, action) =>  state + action.number,
      SUBTRACT: (state, action) =>  state - action.number,
    }, 0);
    
    state$.subscribe(val => console.log(val));
    
    dispatch({
      type: 'ADD',
      number: 10,
    });
    
    dispatch({
      type: 'SUBTRACT',
      number: 15,
    });
    
    dispatch({
      type: 'SUBTRACT',
      number: 0,
    });

提交回复
热议问题