Observable Data Store - Problem
Design and implement an Observable Data Store that allows multiple listeners to be notified whenever data changes. The store should support setting values, getting values, and registering/unregistering listeners.
Your implementation should include:
DataStoreclass with methods to set/get dataaddListener(key, callback)- register a callback for a specific keyremoveListener(key, callback)- unregister a callbackset(key, value)- update value and notify all listeners for that keyget(key)- retrieve current value
When a value changes, all registered listeners for that key should be called with the new value.
Input & Output
Example 1 — Basic Operations
$
Input:
operations = [["addListener","temp",1],["addListener","temp",2],["set","temp",25],["get","temp"]]
›
Output:
[null,null,[1,2],25]
💡 Note:
Add two listeners for 'temp', then set temp=25 which notifies both listeners [1,2], finally get returns 25
Example 2 — Multiple Keys
$
Input:
operations = [["addListener","temp",1],["addListener","light",2],["set","temp",20],["set","light",true]]
›
Output:
[null,null,[1],[2]]
💡 Note:
Separate listeners for different keys: temp change notifies [1], light change notifies [2]
Example 3 — Remove Listener
$
Input:
operations = [["addListener","temp",1],["addListener","temp",2],["removeListener","temp",1],["set","temp",30]]
›
Output:
[null,null,null,[2]]
💡 Note:
After removing listener 1, only listener 2 gets notified when temp changes to 30
Constraints
- 1 ≤ operations.length ≤ 1000
- Each operation is valid according to the method signatures
- Keys are non-empty strings
- Values can be any type (int, string, boolean, etc.)
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code