Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TCA101: Dependency #21

Open
Taehyeon-Kim opened this issue Nov 26, 2023 · 0 comments
Open

TCA101: Dependency #21

Taehyeon-Kim opened this issue Nov 26, 2023 · 0 comments
Labels
Milestone

Comments

@Taehyeon-Kim
Copy link
Owner

import ComposableArchitecture
import Foundation
import XCTestDynamicOverlay

//: Register
struct FactClient {
  var fetch: @Sendable (Int) async throws -> String
}

extension DependencyValues {
  var factClient: FactClient {
    get { self[FactClient.self] }
    set { self[FactClient.self] = newValue }
  }
}

extension FactClient: DependencyKey {
  /// This is the "live" fact dependency that reaches into the outside world to fetch trivia.
  /// Typically this live implementation of the dependency would live in its own module so that the
  /// main feature doesn't need to compile it.
  static let liveValue = Self(
    fetch: { number in
      try await Task.sleep(for: .seconds(1))
      let (data, _) = try await URLSession.shared
        .data(from: URL(string: "http://numbersapi.com/\(number)/trivia")!)
      return String(decoding: data, as: UTF8.self)
    }
  )

  /// This is the "unimplemented" fact dependency that is useful to plug into tests that you want
  /// to prove do not need the dependency.
  static let testValue = Self(
    fetch: unimplemented("\(Self.self).fetch")
  )
}

//: Usage
@Dependency(\.factClient) var factClient
let number: Int = 2
let result = try await factClient.fetch(number)
  • TCA에서 Dependency는 쉽게 관리하고 사용할 수 있다.
  • 위의 예시는 공식 문서의 예제이다.
@Taehyeon-Kim Taehyeon-Kim added this to the Snippets milestone Nov 26, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant