简体   繁体   English

RxSwift:代码第一次工作

[英]RxSwift: code working only first time

I'm new in RxSwift. 我是RxSwift的新手。 Some strange thing happens in my code. 我的代码中发生了一些奇怪的事情。 I have a collection view and 我有一个集合视图和

Driver["String"] 驱动程序[“字符串”]

Data for binding. 绑定数据。

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 fetchImages

Function returns data 函数返回数据

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
    }

Strange thing is this. 奇怪的是这个。 First time when I fetch with "flower" it works and return data, but when I add this code 第一次当我使用“flower”获取时,它可以工作并返回数据,但是当我添加此代码时

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

It doesn't work. 它不起作用。 It doesn't steps in flatmap callback, and because of this, doesn't return anything. 它不会执行flatmap回调,因此,不会返回任何内容。

It works in your first use case, because you're actually using the returned Driver<[String]> via a bindTo() : 它适用于您的第一个用例,因为您实际上是通过bindTo()使用返回的Driver<[String]>

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

However, in your second use case, you aren't doing anything with the returned Driver<[String]> other than saving it to a variable, which you do nothing with. 但是,在您的第二个用例中,您没有对返回的Driver<[String]>执行任何操作,只是将其保存到变量中,而您不执行任何操作。

items = self.fetchImages(text)

A Driver does nothing until you subscribe to it (or in your case bindTo ). 在您subscribe它之前(或者在您的情况下为bindTo ), Driver不执行任何操作。

EDIT: To make this clearer, here's how you could get your second use case to work (I've avoided cleaning up the implementation to keep it simple): 编辑:为了使这个更清楚,这里是你如何让你的第二个用例工作(我已经避免清理实现以保持简单):

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