ios - Rx swift : code working only first time

标签 ios swift rx-swift

我是 RxSwift 的新手。我的代码中发生了一些奇怪的事情。 我有一个 Collection View 和

Driver["String"]

绑定(bind)数据。

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)

这是行不通的。它不会介入平面图回调,因此不会返回任何内容。

最佳答案

它适用于您的第一个用例,因为您实际上使用的是返回的 Driver<[String]>通过 bindTo() :

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

但是,在您的第二个用例中,您没有对返回的 Driver<[String]> 做任何事情。除了将它保存到一个变量之外,您什么都不做。

items = self.fetchImages(text)

A 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)

关于ios - Rx swift : code working only first time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37249413/

相关文章:

ios - 使用 dpkg 构建我自己的包时,应用程序无法在后台运行

ios - 如果应用程序在 iOS 上未激活,我怎么知道联系人已被修改?

ios - 点击按钮时无法识别的选择器错误

arrays - Swift 3 - 使类可迭代

ios - AWS - 通过用户池进行 Cognito 登录和 Cognito 身份验证 [iOS]

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

iphone - 使用 UIAppearance 方法自定义 UIAlertView

swift - 使用 RxSwift 和 URLSession 处理 401 状态

ios - Moya 请求未针对一个提供者启动,但适用于另一提供者

ios - 我的 Sprite Kit 按钮在 Swift 中不起作用