我的自定义RxDelegateProxy立即处置

时间:2018-01-09 20:58:51

标签: ios swift delegates rx-swift rx-cocoa

我有一些第三方库,它有委托方法。但我喜欢使用RX,所以我应该创建RxDelegateProxy以通过RX接收委托的回调。 这是我的自定义DelegateProxy类:

extension Reactive where Base:GalleryController {

  var selectedImages:Observable<(GalleryController, [Image])> {
    let proxy = RxGalleryDelegateProxy.createProxy(for: self.base)
    return proxy.imageSubject.asObservable()
  }

}

private class RxGalleryDelegateProxy: DelegateProxy<GalleryController, GalleryControllerDelegate>, DelegateProxyType, GalleryControllerDelegate {

  private var _imageSubject: PublishSubject<(GalleryController, [Image])>?

  public weak fileprivate(set) var galleryController: GalleryController?

  internal var imageSubject: PublishSubject<(GalleryController, [Image])> {
    if let subject = _imageSubject {
      return subject
    }

    let subject = PublishSubject<(GalleryController, [Image])>()
    _imageSubject = subject

    return subject
  }

  static func currentDelegate(for object: GalleryController) -> GalleryControllerDelegate? {
    return object.delegate
  }

  static func setCurrentDelegate(_ delegate: GalleryControllerDelegate?, to object: GalleryController) {
    object.delegate = delegate
  }

  static func registerKnownImplementations() {
    self.register { RxGalleryDelegateProxy(parentObject: $0) }
  }

  private init(parentObject: GalleryController) {
    self.galleryController = castOrFatalError(parentObject)
    super.init(parentObject: parentObject, delegateProxy: RxGalleryDelegateProxy.self)
  }

  func galleryController(_ controller: GalleryController, didSelectImages images: [Image]) {
    if let subject = _imageSubject {
      subject.on(.next((controller, images)))
    }

    self._setForwardToDelegate(galleryController(controller, didSelectImages: images), retainDelegate: true)
  }

  deinit {
    _imageSubject?.on(.completed)
  }

}

在我的UIViewController中,我订阅了:

final class PhotoLibraryViewController: UIViewController {

  private let _bag = DisposeBag()

  override func viewDidLoad() {
    super.viewDidLoad()

    let gallery = GalleryController()
    present(gallery, animated: true, completion: nil)

    gallery.rx.selectedImages
      .debug("--------")
      .observeOn(MainScheduler.instance)
      .subscribe(onNext: { (controller, images) in
        print("\(images)")
      }, onError: { (error) in
        DDLogError("Error:\n\(error)")
      })
      .disposed(by: _bag)

  }

}

但我通过.debug(“--------”)获得的所有控制台输出都是:

2018-01-09 20:05:14.814: -------- -> subscribed
2018-01-09 20:05:14.817: -------- -> Event completed
2018-01-09 20:05:14.817: -------- -> isDisposed

所以我的目标是在创建之后立即处理。 请问有人能伸出援助之手吗?我做错了什么?

1 个答案:

答案 0 :(得分:-1)

您的gallery对象是在viewDidLoad()内创建的,因此一旦完成viewDidLoad(),就会调用来自deinit的{​​{1}}方法并将其处理掉。

gallery对象移出gallery

viewDidLoad()