rxjs订阅被调用的频率高于预期
我有一个rxjs订阅被调用的频率高于预期,rxjs,Rxjs,我有一个BehaviorSubject函数流。我有一个initialState对象,表示为不可变记录。这些函数被扫描,用于操作状态。代码如下所示: const initialState = Record({ todo: Record({ title: "", }), todos: List([Record({title: "first todo"})()]) }) const actionCreator = (update) => ({ a
BehaviorSubject
函数流。我有一个initialState
对象,表示为不可变记录
。这些函数被扫描,用于操作状态。代码如下所示:
const initialState = Record({
todo: Record({
title: "",
}),
todos: List([Record({title: "first todo"})()])
})
const actionCreator = (update) => ({
addTodo(title) {
update.next((state) => {
console.log({title}); // for debugging reasons
const todo = Record({title})()
return state.set("todos", state.get("todos").push(todo))
})
},
typeNewTodoTitle(title) {
update.next((state) => state.set("todo", state.get("todo").set("title", title))
})
})
const update$ = new BehaviorSubject(state => state);
const actions = actionCreator(update$);
const state = update$.pipe(
scan(
(state, updater) => updater(state), initialState()
),
// share() without share weird things happen
)
我为此编写了一个非常简单的测试
it("should only respond to and call actions once", () => {
const subscripition = chai.spy();
const addTodo = chai.spy.on(actions, 'addTodo');
const typeNewTodoTitle = chai.spy.on(actions, 'typeNewTodoTitle');
state
.pipe(
map(s => s.get("todo")),
distinctUntilChanged()
)
.subscribe(subscripition);
state
.pipe(
map(s => s.get("todos")),
distinctUntilChanged()
)
.subscribe(subscripition);
actions.addTodo('test');
expect(subscripition).to.have.been.called.twice // error
actions.typeNewTodoTitle('test');
expect(subscripition).to.have.been.called.exactly(3) // error
expect(addTodo).to.have.been.called.once
expect(typeNewTodoTitle).to.have.been.called.once
});
});
第一个奇怪的行为是,
subscription
被调用了3次,然后调用了4次,而不是2次,然后调用了3次。第二个奇怪的行为是,尽管每个操作只被调用一次,但是console.log
被调用了两次。我可以通过将share()
添加到管道中来解决此问题,但我不明白为什么需要这样做。您能在一段时间内重现此问题吗?是的,请给我几分钟时间