Skip to content

ComposableEnvironment

tgrapperon edited this page Aug 31, 2021 · 8 revisions

ComposableEnvironment

The base class of your environments.

@dynamicMemberLookup
open class ComposableEnvironment 

Subclass this class to define your feature's environment. You can expose ComposableDependencies values using the Dependency property wrapper and declare child environment using the DerivedEnvironment property wrapper.

For example, if you define:

extension ComposableDependencies {
  var uuidGenerator: () -> UUID {}
  var mainQueue: AnySchedulerOf {}
},

you can declare the LocalEnvironment class, with ChildEnvironment1 and ChildEnvironment2 like:

class LocalEnvironment: ComposableEnvironment {
  @Dependency(\.uuidGenerator) var uuidGenerator
  @Dependency(\.mainQueue) var mainQueue
  @DerivedEnvironment<ChildEnvironment1> var child1
  @DerivedEnvironment<ChildEnvironment2> var child2
}

Initializers

init()

Instantiate a ComposableEnvironment instance with all dependencies sets to their defaults.

public required init() 

After using this initializer, you can chain with(_:_:) calls to set the values of individual dependencies. These values ill propagate to each childDerivedEnvironment as well as their own children DerivedEnvironment.

Methods

with(_:_:)

Use this function to set the values of a given dependency for this environment and all its descendants.

@discardableResult
  public func with<V>(_ keyPath: WritableKeyPath<ComposableDependencies, V>, _ value: V) -> Self 

Calls to this function are chainable, and you can specify any ComposableDependencies KeyPath, even if the current environment instance does not expose the corresponding dependency itself.

For example, if you define:

extension ComposableDependencies {
  var uuidGenerator: () -> UUID {}
  var mainQueue: AnySchedulerOf {}
},

you can set their values in a LocalEnvironment instance and all its descendants like:

LocalEnvironment()
  .with(\.uuidGenerator, { UUID() })
  .with(\.mainQueue, .main)

Clone this wiki locally