Should awareness emit 'change' before removing state?

I thought I might be able to use the awareness change event like this to do some cleanup after a client is removed:

this.wsProvider.awareness.on('change', ({ added, removed }, _conn) => {
  for (let clientId of removed) {
    const stateField = this.wsProvider.awareness.getStates()[clientId]
    // get username from stateField and clean up

Unfortunately, it looks like I can’t get the stateField there, however, because it is removed before the emit call:

Would it be reasonable to emit the change event before this state data is deleted? Or is there another way to get that information at the “tail end” of a client’s departure?

It intended that awareness.getStates() returns the most current state after the change event has been executed. You also wouldn’t expect that awareness.getStates() returns old values, for “update” events.

I think what you are looking for is the old state, before the change happened. Currently, this is not implemented in y-protocols, because this would require the implementation to copy the complete state map every time a change happens. In your application, you could maintain a separate state object that captures the state before the change event.

Side note: Since you are explicitly cleaning up the “username” in your application, also consider that a single user (with the same username) could be logged in several times. This is why you should consider using the unique user-id to maintain user-data.