Open onmyway133 opened 2 years ago
Make a dedicate DebounceObject to debounce (or throttle). Then we can even observe with onChange on the debouncedText or just use it directly to sort
onChange
debouncedText
import Combine public final class DebounceObject: ObservableObject { @Published var text: String = "" @Published var debouncedText: String = "" private var bag = Set<AnyCancellable>() public init(dueTime: TimeInterval = 0.5) { $text .removeDuplicates() .debounce(for: .seconds(dueTime), scheduler: DispatchQueue.main) .sink(receiveValue: { [weak self] value in self?.debouncedText = value }) .store(in: &bag) } } struct SearchView: View { @StateObject var debounceObject = DebounceObject() var body: some View { VStack { TextField(text: $debounceObject.text) .onChange(of: debounceObject.debouncedText) { text in // perform search } } } }
Note for future searchers: I also had to import Combine because AnyCancellable wasn't in scope.
import Combine
AnyCancellable
Make a dedicate DebounceObject to debounce (or throttle). Then we can even observe with
onChange
on thedebouncedText
or just use it directly to sort