Extending target-action methods with RxSwift












1














class A{

func addTarget(target: Any, action: Selector)
}


Let's say I don't have class A source available (framework). How would I extend this class reactively to emit Rx events through an Observable?



I can create a class that just forwards the events through a PublishSubject, but in that case I wouldn't be creating a Reactive extension but doing it through a proxy class.



let a = A()
let del = CustomClassThatAddsItselfAsATarget(a)
del.event.subscribe( ...


instead of



let a = A()
a.rx.event.subscribe( ...









share|improve this question






















  • Can you explain what exactly the problem is with either approach? I do not understand the context of your question.
    – Maxim Volgin
    Nov 21 '18 at 11:33










  • Let's say you create a Reactive extension where Base is the original class. Which object will add itself as a target(addTarget method) to base? Who retains that object? If you create it in the Observable.create closure, it will get deallocated as soon as the Disposable is returned. Should that class retain the observer and push directly onNext events or create a PublishSubject? I can hack something up, but I'm interested if this has already been covered before. The best solution I found so far is the implementation of ControlEvent and ControlTarget which inherits from RxTarget.
    – Mercurial
    Nov 21 '18 at 16:11










  • Does your class A extend UIControl?
    – Daniel T.
    Nov 22 '18 at 2:46










  • @DanielT. Nope.
    – Mercurial
    Nov 22 '18 at 8:45
















1














class A{

func addTarget(target: Any, action: Selector)
}


Let's say I don't have class A source available (framework). How would I extend this class reactively to emit Rx events through an Observable?



I can create a class that just forwards the events through a PublishSubject, but in that case I wouldn't be creating a Reactive extension but doing it through a proxy class.



let a = A()
let del = CustomClassThatAddsItselfAsATarget(a)
del.event.subscribe( ...


instead of



let a = A()
a.rx.event.subscribe( ...









share|improve this question






















  • Can you explain what exactly the problem is with either approach? I do not understand the context of your question.
    – Maxim Volgin
    Nov 21 '18 at 11:33










  • Let's say you create a Reactive extension where Base is the original class. Which object will add itself as a target(addTarget method) to base? Who retains that object? If you create it in the Observable.create closure, it will get deallocated as soon as the Disposable is returned. Should that class retain the observer and push directly onNext events or create a PublishSubject? I can hack something up, but I'm interested if this has already been covered before. The best solution I found so far is the implementation of ControlEvent and ControlTarget which inherits from RxTarget.
    – Mercurial
    Nov 21 '18 at 16:11










  • Does your class A extend UIControl?
    – Daniel T.
    Nov 22 '18 at 2:46










  • @DanielT. Nope.
    – Mercurial
    Nov 22 '18 at 8:45














1












1








1


1





class A{

func addTarget(target: Any, action: Selector)
}


Let's say I don't have class A source available (framework). How would I extend this class reactively to emit Rx events through an Observable?



I can create a class that just forwards the events through a PublishSubject, but in that case I wouldn't be creating a Reactive extension but doing it through a proxy class.



let a = A()
let del = CustomClassThatAddsItselfAsATarget(a)
del.event.subscribe( ...


instead of



let a = A()
a.rx.event.subscribe( ...









share|improve this question













class A{

func addTarget(target: Any, action: Selector)
}


Let's say I don't have class A source available (framework). How would I extend this class reactively to emit Rx events through an Observable?



I can create a class that just forwards the events through a PublishSubject, but in that case I wouldn't be creating a Reactive extension but doing it through a proxy class.



let a = A()
let del = CustomClassThatAddsItselfAsATarget(a)
del.event.subscribe( ...


instead of



let a = A()
a.rx.event.subscribe( ...






swift rx-swift reactive






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 21 '18 at 8:04









MercurialMercurial

1,60331326




1,60331326












  • Can you explain what exactly the problem is with either approach? I do not understand the context of your question.
    – Maxim Volgin
    Nov 21 '18 at 11:33










  • Let's say you create a Reactive extension where Base is the original class. Which object will add itself as a target(addTarget method) to base? Who retains that object? If you create it in the Observable.create closure, it will get deallocated as soon as the Disposable is returned. Should that class retain the observer and push directly onNext events or create a PublishSubject? I can hack something up, but I'm interested if this has already been covered before. The best solution I found so far is the implementation of ControlEvent and ControlTarget which inherits from RxTarget.
    – Mercurial
    Nov 21 '18 at 16:11










  • Does your class A extend UIControl?
    – Daniel T.
    Nov 22 '18 at 2:46










  • @DanielT. Nope.
    – Mercurial
    Nov 22 '18 at 8:45


















  • Can you explain what exactly the problem is with either approach? I do not understand the context of your question.
    – Maxim Volgin
    Nov 21 '18 at 11:33










  • Let's say you create a Reactive extension where Base is the original class. Which object will add itself as a target(addTarget method) to base? Who retains that object? If you create it in the Observable.create closure, it will get deallocated as soon as the Disposable is returned. Should that class retain the observer and push directly onNext events or create a PublishSubject? I can hack something up, but I'm interested if this has already been covered before. The best solution I found so far is the implementation of ControlEvent and ControlTarget which inherits from RxTarget.
    – Mercurial
    Nov 21 '18 at 16:11










  • Does your class A extend UIControl?
    – Daniel T.
    Nov 22 '18 at 2:46










  • @DanielT. Nope.
    – Mercurial
    Nov 22 '18 at 8:45
















Can you explain what exactly the problem is with either approach? I do not understand the context of your question.
– Maxim Volgin
Nov 21 '18 at 11:33




Can you explain what exactly the problem is with either approach? I do not understand the context of your question.
– Maxim Volgin
Nov 21 '18 at 11:33












Let's say you create a Reactive extension where Base is the original class. Which object will add itself as a target(addTarget method) to base? Who retains that object? If you create it in the Observable.create closure, it will get deallocated as soon as the Disposable is returned. Should that class retain the observer and push directly onNext events or create a PublishSubject? I can hack something up, but I'm interested if this has already been covered before. The best solution I found so far is the implementation of ControlEvent and ControlTarget which inherits from RxTarget.
– Mercurial
Nov 21 '18 at 16:11




Let's say you create a Reactive extension where Base is the original class. Which object will add itself as a target(addTarget method) to base? Who retains that object? If you create it in the Observable.create closure, it will get deallocated as soon as the Disposable is returned. Should that class retain the observer and push directly onNext events or create a PublishSubject? I can hack something up, but I'm interested if this has already been covered before. The best solution I found so far is the implementation of ControlEvent and ControlTarget which inherits from RxTarget.
– Mercurial
Nov 21 '18 at 16:11












Does your class A extend UIControl?
– Daniel T.
Nov 22 '18 at 2:46




Does your class A extend UIControl?
– Daniel T.
Nov 22 '18 at 2:46












@DanielT. Nope.
– Mercurial
Nov 22 '18 at 8:45




@DanielT. Nope.
– Mercurial
Nov 22 '18 at 8:45












2 Answers
2






active

oldest

votes


















1














This was a fun exploration. I patterned the below off of how UIControl is set up in RxCocoa.



In answer to your followup questions:




Which object will add itself as a target(addTarget method) to base?




You have to create a class that is designed to do that. I named it ATarget.




Who retains that object?




You make the object conform to Disposable and then it will be retained until disposed of.



extension Reactive where Base: A {

var event: Observable<A> {
return Observable.create { [weak a = self.base] observer in
guard let a = a else {
observer.on(.completed)
return Disposables.create()
}

let aTarget = ATarget(a: a, callback: { a in
observer.on(.next(a))
})

return Disposables.create(with: aTarget.dispose)
}
.takeUntil(deallocated)
}
}

class ATarget: NSObject, Disposable {

typealias Callback = (A) -> Void
let selector: Selector = #selector(ATarget.eventHandler)
weak var a: A?
var callback: Callback?

init(a: A, callback: @escaping Callback) {
self.a = a
self.callback = callback
super.init()
a.addTarget(target: self, action: selector)
}

@objc func eventHandler() {
if let callback = self.callback, let a = self.a {
callback(a)
}
}

func dispose() {
self.a?.removeTarget(target: self)
self.callback = nil
}

}





share|improve this answer























  • Awesome, thanks. I didn't consider conforming to Disposable, that makes sense. The way I solved it is by making a ref cycle in the ATarget class to A, and then setting it to nil in Disposables.create{ } block, but I knew there must be a better way.
    – Mercurial
    Nov 22 '18 at 16:14










  • One thing I'm not sure about is why the .takeUntil(deallocated) is there. Take until what is deallocated?
    – Daniel T.
    Nov 22 '18 at 16:20



















0














RxCocoa and most other RxSwift-based frameworks take the following approach -



public extension Reactive where Base: TheOriginalClass {



See CKRecord+Rx or Bundle+Rx for an example of implementation.



Things get more complicated if you need to provide a proxy delegate, but this is out of scope of this question.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53407609%2fextending-target-action-methods-with-rxswift%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    This was a fun exploration. I patterned the below off of how UIControl is set up in RxCocoa.



    In answer to your followup questions:




    Which object will add itself as a target(addTarget method) to base?




    You have to create a class that is designed to do that. I named it ATarget.




    Who retains that object?




    You make the object conform to Disposable and then it will be retained until disposed of.



    extension Reactive where Base: A {

    var event: Observable<A> {
    return Observable.create { [weak a = self.base] observer in
    guard let a = a else {
    observer.on(.completed)
    return Disposables.create()
    }

    let aTarget = ATarget(a: a, callback: { a in
    observer.on(.next(a))
    })

    return Disposables.create(with: aTarget.dispose)
    }
    .takeUntil(deallocated)
    }
    }

    class ATarget: NSObject, Disposable {

    typealias Callback = (A) -> Void
    let selector: Selector = #selector(ATarget.eventHandler)
    weak var a: A?
    var callback: Callback?

    init(a: A, callback: @escaping Callback) {
    self.a = a
    self.callback = callback
    super.init()
    a.addTarget(target: self, action: selector)
    }

    @objc func eventHandler() {
    if let callback = self.callback, let a = self.a {
    callback(a)
    }
    }

    func dispose() {
    self.a?.removeTarget(target: self)
    self.callback = nil
    }

    }





    share|improve this answer























    • Awesome, thanks. I didn't consider conforming to Disposable, that makes sense. The way I solved it is by making a ref cycle in the ATarget class to A, and then setting it to nil in Disposables.create{ } block, but I knew there must be a better way.
      – Mercurial
      Nov 22 '18 at 16:14










    • One thing I'm not sure about is why the .takeUntil(deallocated) is there. Take until what is deallocated?
      – Daniel T.
      Nov 22 '18 at 16:20
















    1














    This was a fun exploration. I patterned the below off of how UIControl is set up in RxCocoa.



    In answer to your followup questions:




    Which object will add itself as a target(addTarget method) to base?




    You have to create a class that is designed to do that. I named it ATarget.




    Who retains that object?




    You make the object conform to Disposable and then it will be retained until disposed of.



    extension Reactive where Base: A {

    var event: Observable<A> {
    return Observable.create { [weak a = self.base] observer in
    guard let a = a else {
    observer.on(.completed)
    return Disposables.create()
    }

    let aTarget = ATarget(a: a, callback: { a in
    observer.on(.next(a))
    })

    return Disposables.create(with: aTarget.dispose)
    }
    .takeUntil(deallocated)
    }
    }

    class ATarget: NSObject, Disposable {

    typealias Callback = (A) -> Void
    let selector: Selector = #selector(ATarget.eventHandler)
    weak var a: A?
    var callback: Callback?

    init(a: A, callback: @escaping Callback) {
    self.a = a
    self.callback = callback
    super.init()
    a.addTarget(target: self, action: selector)
    }

    @objc func eventHandler() {
    if let callback = self.callback, let a = self.a {
    callback(a)
    }
    }

    func dispose() {
    self.a?.removeTarget(target: self)
    self.callback = nil
    }

    }





    share|improve this answer























    • Awesome, thanks. I didn't consider conforming to Disposable, that makes sense. The way I solved it is by making a ref cycle in the ATarget class to A, and then setting it to nil in Disposables.create{ } block, but I knew there must be a better way.
      – Mercurial
      Nov 22 '18 at 16:14










    • One thing I'm not sure about is why the .takeUntil(deallocated) is there. Take until what is deallocated?
      – Daniel T.
      Nov 22 '18 at 16:20














    1












    1








    1






    This was a fun exploration. I patterned the below off of how UIControl is set up in RxCocoa.



    In answer to your followup questions:




    Which object will add itself as a target(addTarget method) to base?




    You have to create a class that is designed to do that. I named it ATarget.




    Who retains that object?




    You make the object conform to Disposable and then it will be retained until disposed of.



    extension Reactive where Base: A {

    var event: Observable<A> {
    return Observable.create { [weak a = self.base] observer in
    guard let a = a else {
    observer.on(.completed)
    return Disposables.create()
    }

    let aTarget = ATarget(a: a, callback: { a in
    observer.on(.next(a))
    })

    return Disposables.create(with: aTarget.dispose)
    }
    .takeUntil(deallocated)
    }
    }

    class ATarget: NSObject, Disposable {

    typealias Callback = (A) -> Void
    let selector: Selector = #selector(ATarget.eventHandler)
    weak var a: A?
    var callback: Callback?

    init(a: A, callback: @escaping Callback) {
    self.a = a
    self.callback = callback
    super.init()
    a.addTarget(target: self, action: selector)
    }

    @objc func eventHandler() {
    if let callback = self.callback, let a = self.a {
    callback(a)
    }
    }

    func dispose() {
    self.a?.removeTarget(target: self)
    self.callback = nil
    }

    }





    share|improve this answer














    This was a fun exploration. I patterned the below off of how UIControl is set up in RxCocoa.



    In answer to your followup questions:




    Which object will add itself as a target(addTarget method) to base?




    You have to create a class that is designed to do that. I named it ATarget.




    Who retains that object?




    You make the object conform to Disposable and then it will be retained until disposed of.



    extension Reactive where Base: A {

    var event: Observable<A> {
    return Observable.create { [weak a = self.base] observer in
    guard let a = a else {
    observer.on(.completed)
    return Disposables.create()
    }

    let aTarget = ATarget(a: a, callback: { a in
    observer.on(.next(a))
    })

    return Disposables.create(with: aTarget.dispose)
    }
    .takeUntil(deallocated)
    }
    }

    class ATarget: NSObject, Disposable {

    typealias Callback = (A) -> Void
    let selector: Selector = #selector(ATarget.eventHandler)
    weak var a: A?
    var callback: Callback?

    init(a: A, callback: @escaping Callback) {
    self.a = a
    self.callback = callback
    super.init()
    a.addTarget(target: self, action: selector)
    }

    @objc func eventHandler() {
    if let callback = self.callback, let a = self.a {
    callback(a)
    }
    }

    func dispose() {
    self.a?.removeTarget(target: self)
    self.callback = nil
    }

    }






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 22 '18 at 14:34

























    answered Nov 22 '18 at 14:25









    Daniel T.Daniel T.

    13k22534




    13k22534












    • Awesome, thanks. I didn't consider conforming to Disposable, that makes sense. The way I solved it is by making a ref cycle in the ATarget class to A, and then setting it to nil in Disposables.create{ } block, but I knew there must be a better way.
      – Mercurial
      Nov 22 '18 at 16:14










    • One thing I'm not sure about is why the .takeUntil(deallocated) is there. Take until what is deallocated?
      – Daniel T.
      Nov 22 '18 at 16:20


















    • Awesome, thanks. I didn't consider conforming to Disposable, that makes sense. The way I solved it is by making a ref cycle in the ATarget class to A, and then setting it to nil in Disposables.create{ } block, but I knew there must be a better way.
      – Mercurial
      Nov 22 '18 at 16:14










    • One thing I'm not sure about is why the .takeUntil(deallocated) is there. Take until what is deallocated?
      – Daniel T.
      Nov 22 '18 at 16:20
















    Awesome, thanks. I didn't consider conforming to Disposable, that makes sense. The way I solved it is by making a ref cycle in the ATarget class to A, and then setting it to nil in Disposables.create{ } block, but I knew there must be a better way.
    – Mercurial
    Nov 22 '18 at 16:14




    Awesome, thanks. I didn't consider conforming to Disposable, that makes sense. The way I solved it is by making a ref cycle in the ATarget class to A, and then setting it to nil in Disposables.create{ } block, but I knew there must be a better way.
    – Mercurial
    Nov 22 '18 at 16:14












    One thing I'm not sure about is why the .takeUntil(deallocated) is there. Take until what is deallocated?
    – Daniel T.
    Nov 22 '18 at 16:20




    One thing I'm not sure about is why the .takeUntil(deallocated) is there. Take until what is deallocated?
    – Daniel T.
    Nov 22 '18 at 16:20













    0














    RxCocoa and most other RxSwift-based frameworks take the following approach -



    public extension Reactive where Base: TheOriginalClass {



    See CKRecord+Rx or Bundle+Rx for an example of implementation.



    Things get more complicated if you need to provide a proxy delegate, but this is out of scope of this question.






    share|improve this answer




























      0














      RxCocoa and most other RxSwift-based frameworks take the following approach -



      public extension Reactive where Base: TheOriginalClass {



      See CKRecord+Rx or Bundle+Rx for an example of implementation.



      Things get more complicated if you need to provide a proxy delegate, but this is out of scope of this question.






      share|improve this answer


























        0












        0








        0






        RxCocoa and most other RxSwift-based frameworks take the following approach -



        public extension Reactive where Base: TheOriginalClass {



        See CKRecord+Rx or Bundle+Rx for an example of implementation.



        Things get more complicated if you need to provide a proxy delegate, but this is out of scope of this question.






        share|improve this answer














        RxCocoa and most other RxSwift-based frameworks take the following approach -



        public extension Reactive where Base: TheOriginalClass {



        See CKRecord+Rx or Bundle+Rx for an example of implementation.



        Things get more complicated if you need to provide a proxy delegate, but this is out of scope of this question.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 21 '18 at 11:39

























        answered Nov 21 '18 at 9:35









        Maxim VolginMaxim Volgin

        1,8221120




        1,8221120






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53407609%2fextending-target-action-methods-with-rxswift%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Ottavio Pratesi

            Tricia Helfer

            15 giugno