为什么在第一个函数之前订阅处理函数的行为与 onValue 不同?

Why is subscribe handler function behaving different than onValue when preceding by first function?

我有一个产生许多事件的流。我只想在第一个事件发生时激活某些东西。

我的第一个想法是使用 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/

subscribe 方法将使用事件 (https://github.com/baconjs/bacon.js/#event) 对象调用您的方法,而不仅仅是新值。您将获得 2 个回调:一个用于包装在 Next 事件中的实际值,另一个用于 End 事件。如果删除 .first() 部分,结果流将不会结束;这就是为什么在这种情况下你只会得到一个回调。