Y-websocket debounce broadcast and merge updates

I’m using y-websocket to send updates to the back-end. It sends updates to the back-end on every change immediately.
Instead of reacting to every change, I’d like to be able to debounce that and accumulate the changes I need to send.
I’ve managed to achieve debouncing (using my own implementation of y-websocket), but I’m failing at aggregating many update messages (Uinit8Arrays) into one update. I’ve tried using Y.mergeUpdates and Y.mergeUpdatesV2, but the backend ws server is unable to process that message.
Any hints on how to merge these updates that come from the update event handler?

Hi @pgte,

How did you adapt the y-websocket code?

Y.mergeUpdates works on updates, not on messages generated by y-protocols.

const updates = []
ydoc.on('update', update => {
  if (origin !== this) {

// this should be triggered after a debounce
const sendCachedMessages = () => {
  const encoder = encoding.createEncoder()
  encoding.writeVarUint(encoder, messageSync)
  syncProtocol.writeUpdate(encoder, Y.mergeUpdates(updates))
  broadcastMessage(this, encoding.toUint8Array(encoder))

@dmonad Thank you, this is exactly the solution I was looking for!

1 Like