【问题标题】:API call executed only one time using RxSwift使用 RxSwift 只执行一次 API 调用
【发布时间】:2017-03-06 11:15:21
【问题描述】:

我有这个代码似乎是正确的。但它只对第一次搜索更改做出反应。所以代码只执行一次。我尝试将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)
        })
}

【问题讨论】:

  • search 是什么?
  • @ULazdins 变量

标签: swift xcode alamofire rx-swift


【解决方案1】:

您的代码只返回一个Observable。要使用它,您应该观察它(或者更确切地说是在 Rx 术语中subscribe

你可能会想要这样的东西:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-12
    相关资源
    最近更新 更多