Skip to content

How would you create a dependency key for something that has an async initializer? #271

Answered by stephencelis
BrentMifsud asked this question in Q&A
Discussion options

You must be logged in to vote

Generally you should consider dependency values as static interfaces, so the key could be of a sendable closure instead:

static var liveValue: @Sendable () async -> CLMonitor = {
  await CLMonitor("my-location-monitor)
}

Or if you need a long-living monitor, you could wrap it in an actor:

actor Monitor {
  private var _rawValue: CLMonitor?

  var rawValue: CLMonitor {
    get async {
      guard let _rawValue else {
        let rawValue = await CLMonitor("my-location-monitor")
        _rawValue = rawValue
        return rawValue
      }
      return _rawValue
    }
  }
}

// ...
static var liveValue: Monitor { Monitor() }

More work would need to be done to make things testable, though. C…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by BrentMifsud
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants