Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 I wanted to observe an invocation of a method. Is there any way to implement this logic using RxSwift?

I wrote a small example in which I want to dispose a subscription when the test method invokes. But in the subscribe block I can still see a next(6) event. What am I doing wrong?

let subject = PublishSubject<Int>()
subject.takeUntil(self.rx.sentMessage(#selector(test))).subscribe { event in
    print(event)
}

subject.onNext(3)
test()
subject.onNext(6)

//////////////////

func test() {

}
like image 954
Nikita Ermolenko Avatar asked Dec 11 '22 14:12

Nikita Ermolenko


2 Answers

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

like image 79
solidcell Avatar answered Dec 28 '22 06:12

solidcell


you should use dynamic modifier for test function that access to test function is never inlined or devirtualized by the compiler.

like this: dynamic func test() {}

like image 39
zhongwuzw Avatar answered Dec 28 '22 06:12

zhongwuzw