合并:发布者发送文本更改一次

Combine: Publisher sends text change even once

我想观察 UISearchController 文本的变化,这是我的设置(我是 Combine 的新手):

private var searchQuery: String? {
    didSet {
        print(searchQuery)
    }
}

private var disposable: AnyCancellable?


func bindSearchQuery() {
    disposable = searchController.searchBar.publisher(for: \.text)
        .debounce(for: .milliseconds(300), scheduler: DispatchQueue.main)
        .sink { value in
            if let _value = value {
                self.searchQuery = _value
            }
        }
}

而且我只在控制台中看到一次,在加载时:

Optional("")

我必须创建一个 AnyPublisher 对象,然后在 AnyCancellable 对象上接收它的更改:

final class SearchResult {
    var resultText: String? {
        didSet {
            print(resultText)
        }
    }
}

///
@Published var searchQuery: String = ""

private var validateQuery: AnyPublisher<String?, Never> {
    return $searchQuery
        .debounce(for: 0.3, scheduler: RunLoop.main)
        .removeDuplicates()
        .flatMap { query in
            return Future { promise in
                self.search(query: query) { result in
                    switch result {
                    case .success(let _output):
                        print(_output)
                        promise(.success(_output))
                    case .failure:
                        print("Failed search")
                        promise(.success(nil))
                    }
                }
            }
        }
        .eraseToAnyPublisher()
}

private var cancelable: AnyCancellable?
private var result = SearchResult()

///

func bindSearchQuery() {
    cancelable = validateQuery
        .receive(on: RunLoop.main)
        .assign(to: \.resultText, on: result)
}

每次用户在搜索框中输入内容时我都会更新 searchQuery:

func updateSearchResults(for searchController: UISearchController) {
     self.searchQuery = searchController.searchBar.text ?? ""
}