簡體   English   中英

RxSwift:代碼第一次工作

[英]RxSwift: code working only first time

我是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
    }

奇怪的是這個。 第一次當我使用“flower”獲取時,它可以工作並返回數據,但是當我添加此代碼時

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

它不起作用。 它不會執行flatmap回調,因此,不會返回任何內容。

它適用於您的第一個用例,因為您實際上是通過bindTo()使用返回的Driver<[String]>

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

但是,在您的第二個用例中,您沒有對返回的Driver<[String]>執行任何操作,只是將其保存到變量中,而您不執行任何操作。

items = self.fetchImages(text)

在您subscribe它之前(或者在您的情況下為bindTo ), Driver不執行任何操作。

編輯:為了使這個更清楚,這里是你如何讓你的第二個用例工作(我已經避免清理實現以保持簡單):

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM