Nikita Ermolenko Nikita Ermolenko - 2 months ago 47
Swift Question

Observable for selector - RxSwift

I'm trying to migrate my FRP understanding from ReactiveCocoa 2.5 to RxSwift and I have one misunderstanding. In ReactiveCocoa, I used

rac_signalForSelector
when wanted to observe an invocation of a method. Is here any way to implement this logic using RxSwift?

Answer

You can use sentMessage:

class ViewController: UIViewController {

    let disposeBag = DisposeBag()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.rx.sentMessage(#selector(UIViewController.viewWillAppear(_:)))
            .subscribe({ e in
                print(e)
            })
            .addDisposableTo(disposeBag)
    }
}

Outputs:

next([0])

Or another example:

class SomeNSObjectClass: NSObject {
}

class ViewController: UIViewController {

    let disposeBag = DisposeBag()

    override func viewDidLoad() {
        super.viewDidLoad()

        let myObj = SomeNSObjectClass()
        myObjc.rx.sentMessage(NSSelectorFromString("dealloc"))
            .subscribe({ e in
                print(e)
            })
            .addDisposableTo(disposeBag)
        }
    }
}

Outputs:

next([])
completed