Created
December 17, 2021 06:33
-
-
Save alltom/2c0626ad6ba3d3f5a2f9180db19f2e7b to your computer and use it in GitHub Desktop.
Is it this complicated to debounce a search box?
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
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) | |
} | |
} | |
} |
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
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) | |
} | |
} |
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
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