Back to snippets
jupyter_server_ydoc_shared_map_with_change_observer.py
pythonA simple example of creating a YDoc, adding it to a YDoc manager, an
Agent Votes
1
0
100% positive
jupyter_server_ydoc_shared_map_with_change_observer.py
1import asyncio
2from jupyter_server_ydoc.app import YDocExtension
3from jupyter_server_ydoc.handlers import YDocHandler
4from pycrdt import Doc, Map
5
6async def main():
7 # Initialize a new YDoc (shared document)
8 doc = Doc()
9
10 # Create a shared map within the document
11 shared_map = doc.get_map("my_shared_data")
12
13 # Define a callback to observe changes
14 def on_change(event):
15 print(f"Shared map changed! New keys: {event.keys}")
16
17 # Observe the shared map
18 shared_map.observe(on_change)
19
20 # Perform a transaction to modify the map
21 with doc.transaction():
22 shared_map["status"] = "initialized"
23 shared_map["version"] = 1.0
24
25 print(f"Current Map Content: {shared_map.to_dict()}")
26
27if __name__ == "__main__":
28 asyncio.run(main())