* 类型的值没有成员 'rx'

Value of type * has no member 'rx'

我正在尝试为来自 AlamofireImage 的 ImageDownloader 制作一个小型反应式包装器:

import Foundation
import UIKit.UIImage
import AlamofireImage
import RxCocoa
import RxSwift


extension Reactive where Base: ImageDownloader {

    public func download(urlRequest: URLRequest, filter: ImageFilter?) -> Observable<UIImage> {

        return Observable.create { observer in

            self.base.download(urlRequest, filter: filter) { response in

                if let error = response.error {
                    observer.onError(error)
                } else if let image = response.value {
                    observer.onNext(image)
                }
            }
            return Disposables.create()
        }
    }
}

编译没有问题。但是当我尝试在 ImageDownloader 的实例上调用 rx.download 时,我收到一条错误消息,指出那里没有 'rx' 扩展名:

猜猜这是为什么?

您需要先遵守 ReactiveCompatible 协议,然后才能在您的 downloadRequest 调用中使用 'rx'

import AlamofireImage
import RxSwift

extension ImageDownloader: ReactiveCompatible {}

extension Reactive where Base: ImageDownloader {

    public func download(urlRequest: URLRequest, filter: ImageFilter?) -> Observable<UIImage> {

        return Observable.create { observer in
            let requestReceipt = ImageDownloader.default.download(urlRequest, filter: filter) { response in
                if let error = response.error {
                    observer.onError(error)
                } else if let image = response.value {
                    observer.onNext(image)
                    observer.onCompleted()
                }
            }
            return Disposables.create {
               requestReceipt?.request.cancel()
            }
        }
    }
}

现在您可以像下面那样调用 ImageDownloader.default.rx.download(urlRequest:filter:) 方法

let imageRequest = URLRequest.init(url: URL(string: "https://imageserver.com/image/myimage.png")!)
let imageObservable: Observable<UIImage> = ImageDownloader.default.rx.download(urlRequest: imageRequest, filter: nil)