Skip to content

Instantly share code, notes, and snippets.

@alltom
Created December 17, 2021 06:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alltom/2c0626ad6ba3d3f5a2f9180db19f2e7b to your computer and use it in GitHub Desktop.
Save alltom/2c0626ad6ba3d3f5a2f9180db19f2e7b to your computer and use it in GitHub Desktop.
Is it this complicated to debounce a search box?
import SwiftUI
import Combine
struct ContentView: View {
@EnvironmentObject private var model: ViewModel
@StateObject private var searchQuery = SearchQueryDebouncer()
var body: some View {
List {
}
.searchable(text: $searchQuery.query)
.onAppear() {
searchQuery.$debouncedQuery
.assign(to: &model.$searchText)
}
}
}
import SwiftUI
import Combine
class SearchQueryDebouncer: ObservableObject {
@Published var query = ""
@Published var debouncedQuery = ""
private var subscriptions = Set<AnyCancellable>()
init() {
let delayed = $query
.filter { $0 != "" }
.debounce(for: .seconds(1), scheduler: DispatchQueue.main)
let immediate = $query
.filter { $0 == "" }
delayed.merge(with: immediate)
.sink { self.debouncedQuery = $0 }
.store(in: &subscriptions)
}
}
import SwiftUI
import Combine
class ViewModel: NSObject, ObservableObject {
@Published var searchText: String = ""
private var subscriptions = Set<AnyCancellable>()
init() {
$searchText
.receive(on: DispatchQueue.main)
.sink { _ in self.recompute() }
.store(in: &subscriptions)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment