var invariant     = require('./invariant');
var waitForStream = require('./waitForStream');


var stateSubscriptions = [];

var StateStreamMixin = {
  getInitialState: function () {
    invariant(
      typeof this.getStateStream === 'function',
      'When using the StateStreamMixin you must provide a `getStateStream` function in spec'
    );
    
    var stateStream = this.getStateStream(this.props);
    var initializing = true;
    var streamResolved = false;
    var initialState = null;
    
    this.__stateSubscription = stateStream.subscribe(function (val) {
      initialState = val;
      streamResolved = true;
      if (!initializing) {
        this.setState(val);
      }
    }.bind(this));
    
    if (!streamResolved) {
      waitForStream(stateStream);
    }
    
    initializing = false;

    stateSubscriptions.push(this.__stateSubscription);
    
    return initialState;
  }
};


module.exports = StateStreamMixin;
@@ -890,16 +890,297 @@
 lState;%0A
+  %7D,%0A  %0A  componentWillUnmount: function () %7B%0A    if (this.__stateSubscription) %7B%0A      this.__stateSubscription.dispose();%0A      var index = stateSubscriptions.indexOf(this.__stateSubscription);%0A      if (index !== -1) %7B%0A        stateSubscriptions.splice(index, 1);%0A      %7D%0A    %7D%0A
   %7D%0A%7D;%0A%0A

clean stateSubscription on unmounting