Update Programming Guide
@@ -143,12 +143,44 @@ Or clear everything:
|
||||
Ctx.INSTANCE.clear();
|
||||
```
|
||||
|
||||
## Multiple Named Contexts
|
||||
|
||||
You can create and manage multiple independent contexts identified by names.
|
||||
|
||||
```java
|
||||
// Obtain or create named contexts
|
||||
CtxInterface orderCtx = Ctx.INSTANCE.getContext("order");
|
||||
CtxInterface userCtx = Ctx.INSTANCE.getContext("user");
|
||||
|
||||
// Define keys for each context
|
||||
Key<String> orderIdKey = Key.of("orderId", String.class);
|
||||
Key<String> userIdKey = Key.of("userId", String.class);
|
||||
|
||||
// Put values into separate contexts
|
||||
orderCtx.put(orderIdKey, "ORD123");
|
||||
userCtx.put(userIdKey, "USR456");
|
||||
|
||||
// Retrieve independently
|
||||
String orderId = orderCtx.get(orderIdKey);
|
||||
String userId = userCtx.get(userIdKey);
|
||||
```
|
||||
|
||||
You can list all named contexts:
|
||||
|
||||
```java
|
||||
Set<String> contexts = Ctx.INSTANCE.contextNames();
|
||||
System.out.println("Active contexts: " + contexts);
|
||||
```
|
||||
|
||||
Changes in one context do not affect others, allowing modular isolation of data.
|
||||
|
||||
## Best Practices
|
||||
|
||||
* Define your keys as constants to keep them consistent
|
||||
* Register listeners in classes that depend on context changes
|
||||
* Remove listeners when no longer needed (though weak references help)
|
||||
* Use unique key names to avoid collisions
|
||||
* Use unique key names to avoid collisions within each context
|
||||
* Use multiple contexts to logically separate unrelated data
|
||||
|
||||
## Complete Example
|
||||
|
||||
@@ -167,5 +199,7 @@ Ctx.INSTANCE.removeListener(temperatureKey, display);
|
||||
|
||||
Ctx.INSTANCE.put(temperatureKey, 30); // no notification after listener removed
|
||||
```
|
||||
|
||||
---
|
||||
[[Home]] | [[API Reference]] | [[Design and Architecture]] | [[FAQ]] | [[Contributing]]
|
||||
|
||||
|
||||
Reference in New Issue
Block a user