The options that I see are:

  1. There is an array of current chat messages. There is an observable that is created to notify subscribers to new posts. And each new message rushes to the array.

  2. There is an observable that stores in itself an array of all open chat messages at once (or all opened in a session, I don’t know how to do it either). When a new message is received, it is added to the array.

  3. There is an observable that stores only the last message and notifies subscribers about it. That is, if a message is added, then all subscribers trigger functions and add new messages to html, but the entire list is not stored. Well, or stored until the destruction of the component.

If relevant, chat messages are stored in the database and are received via sockets.

Please tell me how it is more convenient, optimized and more intelligent to implement this function? If possible, explain why

    1 answer 1

    I suggest this option.

    The observable does not store a state, only receives an event and sends it to subscribers.

    Chat history exists as a separate object on the server, loaded and cached by the client.

    Data storage on the client depends on the framework, you can use reducer, or SessionStorage for Vanilla JS.

    When sending a message, the client throws out the event, and, since it is subscribed to Observable, when receiving this message, it sets the flag as sent.

    The main advantage of this scheme is high resiliency. When the service crashes, you can resurrect it, or add new instances to the chain in case of high load.

    The main disadvantage is that the story is stored on the client, and over time, the browser can be very loaded. To avoid this, you can use the history pagination and load as you scroll.