In order to solve the problems I’m currently facing, I’ve started implementing a very first custom provider for Yjs, based on an example from the docs:
class customProvider extends Observable {
constructor (sharedDoc) {
super()
sharedDoc.on('update', (update, origin) => {
if (origin !== this) { // ignore updates applied by this provider
console.log('customProvider: update applied on sharedDoc',update)
this.emit('update', [update])
}
})
/**** listen to remote updates ****/
this.on('update', (update) => {
console.log('customProvider: update received from remote',update,arguments)
Y.applyUpdate(sharedDoc, update, this) // "this" is transaction origin
})
}
}
However, it seems that updates made to the sharedDoc from within my business logic will trigger both sharedDoc.on('update',...) and this.on('update',...) - with the latter applying the same update to the sharedDoc again.
Is this really the intended behaviour? Or, how can I avoid reapplying an already applied update within this.on('update',...)?
[Edit] simply adding this to this.emit('update', [update, this]) is not sufficient as the second argument will not be passed to this.on('update', (update, origin) => ...)
I haven’t made a custom provider before, but I am interested in what you come up with. It’s a shame the documentation on this was never completed.
Not sure why you’re subscribing to your own update event instead of just handling it in sharedDoc.on('update')? Maybe I am missing something though.
It may be the case that applyUpdate is idempotent, i.e. already applied updates will be ignored.
I’ve seen this bindState-style function used in various providers before. I think this should form the basis of a custom provider. It syncs the initial state and then watches for updates.
this.on('update',...) came from an example found in the docs - but it should be nonsense (and, after more investigation, I’m quite sure that it is indeed nonsense)
Your bindState looks indeed like a sketch for a custom provider although I would probably put the statements in a different order.
My current knowledge has been put into y-localstorage, together with the additional events I need