Created
September 3, 2018 09:54
-
-
Save JT501/dcdeda31e4704f2af246cfc4e822bcea to your computer and use it in GitHub Desktop.
An extension to avoid duplicate subscriptions in UITableCell & UICollectionViewCell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Created by Johnny on 3/9/2018. | |
// Copyright (c) 2018 [email protected]. All rights reserved. | |
// | |
import UIKit | |
import RxCocoa | |
import RxSwift | |
private var prepareForReuseBag: Int8 = 0 | |
@objc public protocol Reusable : class { | |
func prepareForReuse() | |
} | |
extension UITableViewCell: Reusable {} | |
extension UITableViewHeaderFooterView: Reusable {} | |
extension UICollectionReusableView: Reusable {} | |
extension Reactive where Base: Reusable { | |
var prepareForReuse: Observable<Void> { | |
return Observable.of(sentMessage(#selector(Base.prepareForReuse)).map { _ in }, deallocated).merge() | |
} | |
var reuseBag: DisposeBag { | |
MainScheduler.ensureExecutingOnScheduler() | |
if let bag = objc_getAssociatedObject(base, &prepareForReuseBag) as? DisposeBag { | |
return bag | |
} | |
let bag = DisposeBag() | |
objc_setAssociatedObject(base, &prepareForReuseBag, bag, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) | |
_ = sentMessage(#selector(Base.prepareForReuse)) | |
.subscribe(onNext: { [weak base] _ in | |
let newBag = DisposeBag() | |
objc_setAssociatedObject(base, &prepareForReuseBag, newBag, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) | |
}) | |
return bag | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment