Created
February 24, 2020 00:09
-
-
Save kean/0ea2b3a276c04bf128c9d878a5e79551 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
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