2017-04-25 20 views
0

我有一个周期性触发的事件:Bacon.interval如何停止?

let periodicEvent = Bacon.interval(1000, {}); 
periodicEvent.onValue(() => { 
    doStuff(); 
}); 

我想是暂停和重启periodicEvent当我需要它。 periodicEvent如何暂停和重新启动?或者有没有更好的方法来使用培根?

+0

'whenNeeded'是培根流/ propert以及? – Bergi

回答

1
  1. 不纯的方式做到这一点是增加一个过滤器变量您订阅之前检查,然后修改变量时,你不希望发生的订阅动作:

    var isOn = true; 
    periodicEvent.filter(() => isOn).onValue(() => { 
         doStuff(); 
    }); 
    
  2. “纯-R”的方式做这将是把一个输入的真/假的属性和过滤您根据财产的价值流:

    // make an eventstream of a dom element and map the value to true or false 
    var switch = $('input') 
        .asEventStream('change') 
        .map(function(evt) { 
         return evt.target.value === 'on'; 
        }) 
        .toProperty(true); 
    
    
    var periodEvent = Bacon.interval(1000, {}); 
    
    // filter based on the property b to stop/execute the subscribed function 
    periodEvent.filter(switch).onValue(function(val) { 
        console.log('running ' + val); 
    }); 
    

Here is a jsbin of the above code

使用Bacon.when可能会有更好的/更好用的方法,但我还没有达到那个水平。 :)

+0

绝对不要做不纯的版本,基于属性的过滤是正确的方法。 – OlliM