Skip to content

Instantly share code, notes, and snippets.

@thepearl
Created December 9, 2022 22:54
Show Gist options
  • Save thepearl/d6e3bbf20957a89a49681a63e3c582be to your computer and use it in GitHub Desktop.
Save thepearl/d6e3bbf20957a89a49681a63e3c582be to your computer and use it in GitHub Desktop.
import Foundation
import SwiftUI
import Combine
import Resolver
// MARK: - Presentation Layer
struct MyView: View {
@ObservedObject var viewModel: MyViewModel
var body: some View {
Text(viewModel.data)
}
}
// MARK: - Domain Layer
class MyViewModel: ObservableObject {
@Published var data: String = ""
@Injected private var dataFetcher: DataFetcher
private var cancellable: AnyCancellable?
func fetchData() {
// Fetch data from the network or a local database
// using the data access layer
func fetchData() {
cancellable = dataFetcher.fetchData()
// Handle the result of the fetch
.receive(on: RunLoop.main)
.sink { error in
if case let .failure(error) = error {
print(error.localizedDescription)
}
} receiveValue: { (value: String) in
self.data = value
}
}
}
}
// MARK: - Data Access Layer
protocol DataFetcher {
func fetchData() -> AnyPublisher<String, Error>
}
class NetworkDataFetcher: DataFetcher {
func fetchData() -> AnyPublisher<String, Error> {
// Fetch data from the network and call the completion handler
Just("Hello")
.setFailureType(to: Error.self)
.eraseToAnyPublisher()
}
}
class DatabaseDataFetcher: DataFetcher {
func fetchData() -> AnyPublisher<String, Error> {
// Fetch data from the local database and call the completion handler
Just("Mom")
.setFailureType(to: Error.self)
.eraseToAnyPublisher()
}
}
// MARK: - Dependency Injection
extension Resolver {
public static func registerMyViewModel() {
register { MyViewModel(dataFetcher: $0) }
.implements(MyViewModel.self)
.resolve(using: DataFetcher.self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment