title: Unsubscribe from Redux store when condition is true?
body: <p>I'm employing <a href="https://github.com/reactjs/redux/issues/303#issuecomment-125184409" rel="nofollow">the suggestion from @gaearon</a> to setup a listener on my redux store. I'm using this format:</p>
  
  <pre><code>function observeStore(store, select, onChange) {
    let currentState;
  
    if (!Function.prototype.isPrototypeOf(select)) {
      select = (state) =&gt; state;
    }
  
    function handleChange() {
      let nextState = select(store.getState());
      if (nextState !== currentState) {
        currentState = nextState;
        onChange(currentState);
      }
    }
  
    let unsubscribe = store.subscribe(handleChange);
    handleChange();
    return unsubscribe;
  }
  </code></pre>
  
  <p>I'm using this in an <code>onEnter</code> handler for a <code>react-router</code> route:</p>
  
  <pre><code>Entity.onEnter = function makeFetchEntity(store) {
    return function fetchEntity(nextState, replace, callback) {
      const disposeRouteHandler = observeStore(store, null, (state) =&gt; {
        const conditions = [
          isLoaded(state.thing1),
          isLoaded(state.thing2),
          isLoaded(state.thing3),
        ];
  
        if (conditions.every((test) =&gt; !!test) {
          callback(); // allow react-router to complete routing
          // I'm done: how do I dispose the store subscription???
        }
      });
  
      store.dispatch(
        entities.getOrCreate({
          entitiesState: store.getState().entities,
          nextState,
        })
      );
    };
  };
  </code></pre>
  
  <p>Basically this helps gate the progression of the router while actions are finishing dispatching (async).</p>
  
  <p>My problem is that I can't figure out where to call <code>disposeRouteHandler()</code>. If I call it right after the definition, my <code>onChange</code> function never gets a chance to do it's thing, and I can't put it inside the <code>onChange</code> function because it's not defined yet.</p>
  
  <p>Appears to me to be a chicken-egg problem. Would really appreciate any help/guidance/insight.</p>