2017-11-14 7 views
0

많은 이벤트를 생성하는 스트림이 있습니다. 그 일이 생길 때 특정 물건을 활성화하기 위해서만 첫 번째 이벤트를하고 싶습니다.첫 번째 함수 앞에 선행 할 때 구독 처리 함수가 onValue와 다른 동작을하는 이유는 무엇입니까?

첫 번째 생각은이를 달성하기 위해 stream.first(). subscribe (activateStuff)를 사용하는 것이 었습니다. 문제는 activateStuff 핸들러가 두 번 호출되는 것입니다. 하지만 구독 대신 onValue를 사용하면 예상 한 번만 호출됩니다.

흥미롭게도 first() 부분을 제거하고 하나의 이벤트가 시작되면서 subscribe를 사용하면 onValue (둘 다 activateStuff를 한 번만 호출)처럼 동작합니다.

let stream1 = new Bacon.Bus(); 
stream1.first().onValue(() => console.log("from stream1")); 
stream1.push({}); 
// it will print from stream1 once 

let stream2 = new Bacon.Bus(); 
stream2.first().subscribe(() => console.log("from stream2")); 
stream2.push({}); 
// it will print from stream2 twice. Why !? 

let stream3 = new Bacon.Bus(); 
stream3.onValue(() => console.log("from stream3")); 
stream3.push({}); 
// it will print from stream3 once 

let stream4 = new Bacon.Bus(); 
stream4.subscribe(() => console.log("from stream4")); 
stream4.push({}); 
// it will print from stream4 once 

동일한 이벤트 스트림으로 first() 및 subscribe()를 사용하면 무엇이 좋을까요?

당신은 여기에 코드를 재생할 수 있습니다 : https://fiddle.jshell.net/np0r80fn/

답변

0

subscribe 방법은 이벤트 (https://github.com/baconjs/bacon.js/#event)와 메소드를 호출 대신 새 값의 객체. 2 개의 콜백을 얻습니다. 하나는 Next 이벤트에 랩핑 된 실제 값이고 다른 하나는 End 이벤트입니다. .first() 부분을 제거하면 결과 스트림이 종료되지 않습니다. 그래서 그 경우 콜백이 하나만 나오는 이유입니다.