swift - API 调用仅使用 RxSwift 执行一次

标签 swift xcode alamofire rx-swift

我的这段代码似乎是正确的。但它只会对第一次搜索更改使用react。所以代码只执行一次。我尝试将 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)
        })
}

最佳答案

您的代码只返回一个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

关于swift - API 调用仅使用 RxSwift 执行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42624179/

相关文章:

ios - 有没有办法在 Swift 中自定义 Firebase 电话身份验证发送的短信?

Swift - 为什么我不能从此 NSDictionary 对象返回 NSNumber 或 Double 数据类型?

swift - 如何避免强制展开变量?

iphone - NSRangeException 问题

ios - 如何在ios中更改svg图像的颜色?

ios - 如何使用 Alamofire 将数据发布到服务器 API/注册用户?

ios - 在自动布局 xcode 之后更改 View 并将其更改为原始 View

ios - 在 MFMailComposeViewController 的 messageBody 中查找字符串

ios - 在 Swift 中写入 Google 表格

ios - swift 3 [字符串 : AnyObject]() gives Cannot call value of non-function type UInt -> Data