我有这个代码似乎是正确的。但它只会对第一次搜索更改做出反应。所以代码只执行一次。我尝试将concat(Observable.never())
添加到我的getAl函数中,但它仍然只运行一次。我错过了什么 ?
exists = search.asObservable()
.throttle(0.3, scheduler: MainScheduler.instance)
.distinctUntilChanged()
.flatMapLatest { searchString -> Observable<Bool> in
guard !searchString.isEmpty else {
return Observable.empty()
}
return ServiceProvider.food.getAll(whereFoodName: searchString)
.flatMap({ (result) -> Observable<Bool> in
return Observable.just(result.count > 0)
})
}
答案 0 :(得分:0)
您的代码只返回Observable
。要使用它,您应该观察它(或者更确切地说是subscribe
在Rx术语中)
你可能想要这样的东西:
search.asObservable()
.throttle(0.3, scheduler: MainScheduler.instance)
.distinctUntilChanged()
.subscribe(onNext: { searchString in
let exists = ServiceProvider.food.getAll(whereFoodName: searchString).count > 0
print("Exists: \(exists)")
// Or do whatever you want with `exists` constant
// You could call a method to update UI
if exists {
self.button.enabled = true
}
})
.disposed(by: disposeBag) //disposeBag should be your property which will be deallocated on deinit