Jiss
Jiss

Reputation: 35

How to implement rxswift's methodInvoked function in the combine framework

I am currently using rxswift, but am studying the combine framework.

I used the methodInvoked function a lot in rxswift.

Is it possible to create functionality like methodInvoked method in combine framework?

public extension Reactive where Base: UIViewController {
    var viewWillAppear: Observable<[Any]> {
        return methodInvoked(#selector(UIViewController.viewWillAppear(_:)))
    }
    
    var viewDidAppear: Observable<[Any]> {
        return methodInvoked(#selector(UIViewController.viewDidAppear(_:)))
    }
    
    var viewDidDisappear: Observable<[Any]> {
        return methodInvoked(#selector(UIViewController.viewDidDisappear(_:)))
    }
    
    var viewWillDisappear: Observable<[Any]> {
        return methodInvoked(#selector(UIViewController.viewWillDisappear(_:)))
    }
}

I want to implement the methodInvoked function like the code above using the combine framework.

Upvotes: 1

Views: 566

Answers (2)

Ting Yi Shih
Ting Yi Shih

Reputation: 896

Somebody seemed to bring up a solution: https://github.com/chorim/CombineInterception.

With this you are able to add it to your project:

.package(url: "https://github.com/edudo-inc/CombineCocoa.git", from: "0.2.1")

and import CombineInterception so you may call something like

viewController.publisher(for: #selector(UIViewController.viewDidLoad))

However this is just a forked repo that has not been formally merged into CombineCocoa. If you have no concern about the authenticity, you might either add the package to your project or just clone the repo into your project until this implementation gets formally acknowledged by CombineCocoa.

Upvotes: -1

Scott Thompson
Scott Thompson

Reputation: 23711

Yes, it is possible to reproduce that functionality for methods written in Objective-C. The technique for replacing an Objective-C method with a custom implementation (that may, or may not, invoke the original method definition) is often called "Monkey Patching" or "Method Swizzling" and you can find techniques for doing so through Google. Here is an example:

https://nshipster.com/method-swizzling/

To implement the same thing with combine, you would probably use a PassthroughSubject that gets type erased to an AnyPublisher and have your replacement Objective-C method send a value to the subject each time the method is invoked.

Upvotes: 1

Related Questions