I have a function, that gets called twice by an observe
function. As you can see, in the addMessage
function, there is a check that if it is called with the same messge, it return
s.
My problem is, that the addMessage
function is getting called twice with the same message.
I think the reason is because it is being done quickly before the first message has been added, the second message is executed already.
What is the best way to synchronize the messages, that the first one is given time to save, before the second one is processed?
this.messages.observe({
changed: (newMessage, oldMessage) => this.addMessage(newMessage)
});
and
private addMessage(message: Message): void {
let foundMessage: Message = this.localMessageCollection.findOne({ _id: message._id });
if (foundMessage && foundMessage._id === message._id) {
console.log('addMessage(found): '+message._id+' '+message.content);
return;
}
console.log('addMessage: '+message._id+' '+message.content);
this.addLocalMessage(message);
this.chatsStorageService.addMessage(this.activeChat, message).then((messageData: Message) => {
let data = {
chat: this.activeChat,
messageString: this.messageString,
sendMessage: true
}
this.events.publish('messages:update', data);
});
}