SwiftUI和Combine可观察对象已@Published正在不断发布

SwiftUI和Combine可观察对象已@Published正在不断发布,swiftui,combine,Swiftui,Combine,我有这样一个搜索栏的视图模型,它对输入到搜索栏中的术语进行了搜索。然后它发出请求并分配给结果 class SearchViewModel<T>: ObservableObject { @Published var searchTerm = "" @Published var results: [T] = [] private var disposables = Set<AnyCancellable>() init() {

我有这样一个搜索栏的视图模型,它对输入到搜索栏中的术语进行了搜索。然后它发出请求并分配给结果

class SearchViewModel<T>: ObservableObject {

    @Published var searchTerm = ""
    @Published var results: [T] = []

    private var disposables = Set<AnyCancellable>()

    init() {
        $searchTerm
            .debounce(for: .seconds(1), scheduler: DispatchQueue.global())
            .flatMap { term in
                self.search(by: term)
            }
            .print("searching")
            .assign(to: \.results, on: self)
            .store(in: &disposables)
    }

    open func search(by term: String) -> AnyPublisher<[T], Never> {
        fatalError()
    }
}
这很奇怪,因为这应该只在字段中键入的输入项上触发

我想这里有点不对劲

更新


重要信息:此多个搜索流日志显示在控制台中,其中有汉堡包菜单中的拖动,如果使用条形按钮显示,则只有一次刷新。有点奇怪的是,显示视图或者用偏移量移动视图会导致@Published var term获得新的输入,而且我看到我的列表内容正在刷新

使用它的测试环境并不明显,但在这一点上,我使用过滤器进行了重构,如下所示

.debounce(for: .seconds(1), scheduler: DispatchQueue.global())
.filter { !$0.isEmpty }
无论如何,在这样的用例中,避免重新搜索相同的术语也是有用的

.debounce(for: .seconds(1), scheduler: DispatchQueue.global())
.filter { !$0.isEmpty }