How do I debounce text input in Combine with Swift?

debounce, Combine, Swift, text input
This page explains how to debounce text input using Combine in Swift, allowing you to process input efficiently and reduce unnecessary operations.

import SwiftUI
import Combine

struct ContentView: View {
    @State private var searchText: String = ""
    private var cancellables = Set()

    var body: some View {
        VStack {
            TextField("Search...", text: $searchText)
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .padding()
        }
        .onAppear {
            setupDebounce()
        }
    }

    private func setupDebounce() {
        $searchText
            .debounce(for: .milliseconds(300), scheduler: RunLoop.main)
            .sink { input in
                // Process the debounced input here
                print("Debounced input: \(input)")
            }
            .store(in: &cancellables)
    }
}
    

debounce Combine Swift text input