How to deepObserve subdocuments?

As part of evaluating Yjs for my company, I’m trying to understand how to observe a tree of subdocuments. In the following example, there is a root document and a child document.

const Y = require("yjs");

const rootDoc = new Y.Doc();
const rootMap = rootDoc.getMap();

rootMap.observeDeep((events) => {
  for (const event of events) {
    console.log(event.keysChanged);
  }
});

const childDoc = new Y.Doc();
const childMap = childDoc.getMap();

childMap.set("prop-x", "val-x");
rootMap.set("child-x", childDoc);
childMap.set("prop-x", "val-x2");
rootMap.delete("child-x");

I am expecting to see 4 different invocations of console.log, corresponding to the 4 different transactions.

But I’m only observing 2 messages on the console.

Set(1) { ‘child-x’ }
Set(1) { ‘child-x’ }

These are corresponding to the the rootMap.set and rootMap.delete operations.

Why doesn’t observeDeep get invoked for operations on the childMap?

Thanks in advance!

Chris

1 Like

I also ran into this issue and ended up writing stuff myself to check which subdocs were added or removed with doc.on("subdocs", listener), and then start observing the newly added docs.

I haven’t found the difference between observe and observeDeep yet, will probably dive into the source to figure out the difference.

@bbss Thanks for confirming this. For sure, observeDeep doesn’t work as expected with Map shared data type. Have you found the “subdocs” listener to work reliably? E.g. I see both “added” and “loaded” events fired whenever new subdocument is added to the parent. I still haven’t understood the purpose of the “loaded” event.

I think the purpose of loaded is that when there are big (nested) documents you don’t need to load all of them on each client unless demanded. Otherwise Yjs documents would grow too fast.

As for reliability, I’ve built an ad-hoc version that covers most of my use-cases so far, but doing some dirty stuff to keep that “reactive” in my React app including using timeouts here and there, which is bad. Have been playing wack-a-mole with issues as they appeared to get a proof of concept, and that seems to work fairly well now.

Next phase will be more well thought out and using more automated tests.

1 Like