Skip to content

Instantly share code, notes, and snippets.

@vinhnx
Created March 2, 2021 11:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vinhnx/74d3a1f74afa0b64e9da72e762ccc28d to your computer and use it in GitHub Desktop.
Save vinhnx/74d3a1f74afa0b64e9da72e762ccc28d to your computer and use it in GitHub Desktop.
SwiftUI with MVVM example
// 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>
}
@Connor98web
Copy link

A great example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment