0

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 returns.

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);
    });
  }
Richard
  • 8,193
  • 28
  • 107
  • 228
  • 1
    I don't know what `localMessageCollection` is exactly, but does it support an atomic `upsert` operation, or something to that effect? Instead of a race-condition-prone *check-then-insert*, do an *insert-if-not-exists*. – deceze Oct 06 '16 at 12:42
  • Otherwise you simply keep a local array of messages not yet processed… `if (this.messagesInProgress.indexOf(message) > -1) { return; }` – deceze Oct 06 '16 at 12:44
  • 1
    I wonder why `findOne` is synchronous but `addMessage` isn't… – Bergi Oct 06 '16 at 13:03
  • What does `addLocalMessage` do? Isn't it synchronous? – Bergi Oct 06 '16 at 13:04
  • It just adds the message to an array. Just a one liner – Richard Oct 06 '16 at 13:05
  • `localMessageCollection` is a `Mongo.Collection` – Richard Oct 06 '16 at 13:07
  • I think I will keep an array of processed messages unless someone suggests a better answer for now – Richard Oct 06 '16 at 13:09
  • @Richard Is it the `localMessageCollection` one? In that case, your code should work already. Maybe post the definitions of `addLocalMessage` and `findOne`. – Bergi Oct 06 '16 at 13:11
  • You will want to have a look at [Limit concurrency of promise being run](http://stackoverflow.com/q/38778723/1048572) – Bergi Oct 06 '16 at 13:11
  • Yes, `this.localMessageCollection` is being updated, but I think the second message is entering before the update is completed. – Richard Oct 06 '16 at 13:23

0 Answers0