Created
March 2, 2021 11:04
-
-
Save vinhnx/74d3a1f74afa0b64e9da72e762ccc28d to your computer and use it in GitHub Desktop.
SwiftUI with MVVM example
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
// https://kean.blog/post/swiftui-data-flow | |
struct SearchView: View { | |
@ObservedObject var viewModel: SearchViewModel | |
var body: some View { | |
VStack { | |
TextField("Search", text: $viewModel.query) | |
List(viewModel.songs) { | |
Text($0.name) | |
} | |
} | |
} | |
} | |
final class SearchViewModel: ObservableObject { | |
@Published var query: String = "" | |
@Published private(set) var songs: [Song] = [] | |
private var cancellable: AnyCancellable? | |
init(service: SearchService) { | |
cancellable = $query | |
.throttle(for: .milliseconds(300), scheduler: DispatchQueue.main) | |
.removeDuplicates() | |
.flatMap { | |
service.searchSongs(query: $0).catch { | |
_ in Just([]) | |
} | |
} | |
.receive(on: DispatchQueue.main) | |
.sink { [unowned self] in self.songs = $0 } | |
} | |
} | |
final class SearchService { | |
func searchSongs(query: String) -> Future<[Song], Error> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A great example