繁体   English   中英

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

[英]Incorrect value in observable subscribe function

我已经使用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内部功能不能保证执行顺序吗?

您在更改值之前先进行记录...这就是为什么它显示为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())        
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM