Created
December 9, 2022 22:54
-
-
Save thepearl/d6e3bbf20957a89a49681a63e3c582be to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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