Created
December 9, 2022 22:41
-
-
Save thepearl/4f3fe16fb37405a4f69c93bfca019687 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
// 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 = "" | |
private let dataFetcher: DataFetcher | |
private var cancellable: AnyCancellable? | |
init(dataFetcher: DataFetcher) { | |
self.dataFetcher = dataFetcher | |
} | |
func fetchData() { | |
// Fetch data from the network or a local database | |
// using the data access layer | |
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() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment