-
-
Notifications
You must be signed in to change notification settings - Fork 17
Closed
Labels
enhancementNew feature or requestNew feature or request
Description
Checklist
- Reviewed the README and documentation.
- Checked existing issues & PRs to ensure not duplicated.
Description
This proposal introduces a dedicated lifecycle hook in AtomEffect (e.g., willCreate) to handle setup/teardown logic before the atom's value is initialized, avoiding side effects in defaultValue and aligning with SwiftUI-like lifecycle patterns.
Example Use Case
For atoms requiring setup (e.g., battery monitoring, location tracking):
struct BatteryStatusAtom: StateAtom, Hashable {
func defaultValue(context: Context) -> Float {
// ✅ No side effects here; value creation remains pure
return UIDevice.current.batteryLevel
}
func effect(context: CurrentContext) -> BatteryObserveEffect {
BatteryObserveEffect()
}
class BatteryObserveEffect: AtomEffect {
func willCreate(context: Context) {
// ✅ Setup logic moved here
UIDevice.current.isBatteryMonitoringEnabled = true
}
func released(context: Context) {
UIDevice.current.isBatteryMonitoringEnabled = false
}
}
}Alternative Solution
Continue using defaultValue for setup logic, but this:
- Violates the pure function contract of
defaultValue - Forces cleanup to be deferred to
released, creating temporal coupling - Reduces code clarity for stateful initialization
Proposed Solution
Add a new function to AtomEffect:
protocol AtomEffect {
func willCreate(context: Context) // Called before value creation
// Existing: released(context:)
}Motivation & Context
Why?
- Current workarounds (e.g., putting setup in
defaultValue) compromise API design integrity. - SwiftUI's Coordinator pattern demonstrates the value of lifecycle hooks for resource management (
make/dismiss). - Explicit setup/teardown improves code readability and aligns with atomic state management principles.
Reference
Discussed in PR #136: swiftui-atom-properties#136
Metadata
Metadata
Assignees
Labels
enhancementNew feature or requestNew feature or request