I have written a custom event bus using BehaviorSubject. It simply executes the subscription passed by a subscriber when a publisher publishes an event. The event bus logic seems to work correctly, but my local variables are not updating correct when the subscription executes. Following is the code:
It's a simple logic that checks if the menu property of map object is false, then it does some work and sets it to true so that the same logic doesn't get executed twice when the subscription is called again.
Issue: For some reason, when the subscription is called second time, the menu property is still false. I understand the js asynchronous behaviour, but things aren't adding up this time for me.
Following is the output:
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=========
The issue is at 679th milliseconds. When the object property was set to true at 678th millseconds, why is it showing false at 679th millisecond?
Edit: If it would have been an other multithreaded language like Java, I would have assumed that order of execution is NOT guaranteed. The execution at a later time (679) might still be getting older value of this.map["menu"] because threads might not be syncronized. But this being single threaded Javascript, it is guaranteed that execution of code at 679 is done after changing the variable at 678. Nothing changes that fact, like the value of result etc..
Edit: Can BehaviourSubject
be the culprit here? Can it be that by some means internal functioning of BehaviourSubject
doesn't guarantee order of execution?