2016-05-16 121 views
3

我是RxSwift的新手。一些奇怪的事情发生在我的代码中。 我有用于结合的集合视图和RxSwift:代码只能第一次工作

驱动程序[ “字符串”]

数据。

var items = fetchImages("flower") 
items.asObservable().bindTo(self.collView.rx_itemsWithCellIdentifier("cell", cellType: ImageViewCell.self)) { (row, element, cell) in 
      cell.imageView.setURL(NSURL(string: element), placeholderImage: UIImage(named: ""))   
}.addDisposableTo(self.disposeBag) 

fetchImages

函数返回的数据

private func fetchImages(string:String) -> Driver<[String]> { 

     let searchData = Observable.just(string) 
     return searchData.observeOn(ConcurrentDispatchQueueScheduler(globalConcurrentQueueQOS: .Background)) 
      .flatMap 
      { text in // .Background thread, network request 

       return RxAlamofire 
        .requestJSON(.GET, "https://pixabay.com/api/?key=2557096-723b632d4f027a1a50018f846&q=\(text)&image_type=photo") 
        .debug() 
        .catchError { error in 
         print("aaaa") 
         return Observable.never() 
       } 
      } 
      .map { (response, json) -> [String] in // again back to .Background, map objects 
       var arr = [String]() 
       for i in 0 ..< json["hits"]!!.count { 
        arr.append(json["hits"]!![i]["previewURL"]!! as! String) 
       } 

       return arr 
      } 
      .observeOn(MainScheduler.instance) // switch to MainScheduler, UI updates 
      .doOnError({ (type) in 
       print(type) 
      }) 
      .asDriver(onErrorJustReturn: []) // This also makes sure that we are on MainScheduler 
    } 

奇怪的事情是这样的。第一次当我用“花朵”取回它的工作原理并返回数据时,但是当我添加此代码时

self.searchBar.rx_text.subscribeNext { text in 
     items = self.fetchImages(text) 
}.addDisposableTo(self.disposeBag) 

它不起作用。它不会在flatmap回调中进行操作,因此,不会返回任何内容。

回答

4

它可以在您第一次使用的情况下,因为你实际上是通过bindTo()使用返回Driver<[String]>

var items = fetchImages("flower") 
items.asObservable().bindTo(... 

然而,在你的第二个使用的情况下,你是不是做与返回Driver<[String]>什么除了将它保存到一个变量中,你什么也不做。

items = self.fetchImages(text) 

一个Driver什么也不做,直到你subscribe它(或你的情况bindTo)。

编辑:为了更清楚,这里是你如何能得到你的第二个用例的工作(我避免清理执行,以保持它的简单):

self.searchBar.rx_text 
.flatMap { searchText in 
    return self.fetchImages(searchText) 
} 
.bindTo(self.collView.rx_itemsWithCellIdentifier("cell", cellType: ImageViewCell.self)) { (row, element, cell) in 
    cell.imageView.setURL(NSURL(string: element), placeholderImage: UIImage(named: ""))   
}.addDisposableTo(self.disposeBag) 
+0

是的,我同意了,但问题是,第二次self.fetchImages(文本)不会返回任何东西,RxAlamofire .requestJSON does not call.It接缝flatmap回调doesnt步骤,因为该呼叫does not调用 –

+0

你是什么意思的“第二次” ?你已经展示了你的'fetchImages'的两种不同用途。你的意思是你同时使用两种方法,而第二种方式如果迟一点就不起作用了?或者你的意思是说你只使用最后一个用例,它确实有效,但只有一次? – solidcell

+0

我使用两个,第一次我用“花朵”和它的返回数据调用函数,第二次我使用搜索栏中的文本,它不返回任何东西。 –