可观察的订阅函数中的值不正确

时间:2018-07-05 03:09:01

标签: javascript asynchronous observable behaviorsubject subject-observer

我已经使用BehaviorSubject编写了一个自定义事件总线。当发布者发布事件时,它仅执行订阅者传递的订阅。事件总线逻辑似乎正常工作,但是执行订阅时我的局部变量未正确更新。以下是代码:

这是一个简单的逻辑,它检查map对象的menu属性是否为false,然后做一些工作并将其设置为true,这样当再次调用订阅时,相同的逻辑就不会执行两次。

问题: 由于某种原因,当第二次调用订阅时,菜单属性仍为false。我了解js异步行为,但是这次对我来说并没有增加任何东西。

以下是输出:

console.log("1 : " + this.map["menu"]);
console.log("time in milliseconds" + +new Date());

this.eventBus.getEventBusSubscription<Boolean>(this.eventBus.KEY, false)

.subscribe(result => {

    console.log("2 : " + this.map["menu"]);
    console.log("time in milliseconds" + +new Date())

    if (!this.map["menu"]) {
      this.map["menu"] = true

      console.log("3 : " + this.map["menu"]);
      console.log("time in milliseconds" + +new Date());


    }
    console.log("=======END=========")

});

[Log] 1 : false
[Log] time in milliseconds374

[Log] 2 : false
[Log] time in milliseconds678
[Log] 3 : true
[Log] time in milliseconds678
[Log] =======END=========

[Log] 2 : false
[Log] time in milliseconds679
[Log] 3 : true
[Log] time in milliseconds679
[Log] =======END=========

问题出现在第679毫秒。当object属性在678毫秒处设置为true时,为什么它在679毫秒处显示为false?

编辑:如果本来应该是Java之类的其他多线程语言,那么我将假定不能保证执行顺序。稍后的执行(679)可能仍会获得this.map [“ menu”]的旧值,因为线程可能未同步。但是,由于这是单线程Javascript,因此可以确保在678处更改变量后才执行679处的代码执行。不会改变该事实,例如result的值等。

编辑:BehaviourSubject是这里的罪魁祸首吗?可以通过某种方式BehaviourSubject的内部功能不能保证执行顺序吗?

1 个答案:

答案 0 :(得分:0)

您在更改值之前先进行记录...这就是为什么它显示为false。

 if (!this.map["menu"]) {
    console.log("3 : " + this.map["menu")
    console.log("time in milliseconds" + new Date().getMilliseconds())

    this.map["menu"] = true
  }

应该是

 if (!this.map["menu"]) {
    this.map["menu"] = true
    console.log("3 : " + this.map["menu")
    console.log("time in milliseconds" + new Date().getMilliseconds())        
  }