Skip to content

Instantly share code, notes, and snippets.

@kean
Created February 24, 2020 00:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kean/0ea2b3a276c04bf128c9d878a5e79551 to your computer and use it in GitHub Desktop.
Save kean/0ea2b3a276c04bf128c9d878a5e79551 to your computer and use it in GitHub Desktop.
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, latest: true)
.removeDuplicates()
.flatMap {
service.searchSongs(query: $0).catch {
_ in Just([])
}
}
.receive(on: DispatchQueue.main)
.assign(to: \.songs, on: self)
}
}
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