Skip to content

[Feature Request]: Add Lifecycle Hook to AtomEffect for Setup Logic #168

@strangeliu

Description

@strangeliu

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:

  1. Violates the pure function contract of defaultValue
  2. Forces cleanup to be deferred to released, creating temporal coupling
  3. 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

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions