Signals icon indicating copy to clipboard operation
Signals copied to clipboard

Pass observer to the callback closure, to avoid retain cycle or [weak self] boilerplate

Open acecilia opened this issue 7 years ago • 5 comments

Would it make sense to pass the observer as a parameter in the callback closure? Something like:

public func subscribe(with observer: ObserverType, callback: @escaping (ObserverType, T) -> T) -> Signals.SignalSubscription<ObserverType, T>

This will allow to convert this:

        signal.subscribe(with: self) { [weak self] (newValue) in
            guard let weakSelf = self else { return } // Boilerplate + easy to forget

            weakSelf.property = newValue
        }

Or this:

        signal.subscribe(with: self) { (newValue) in
            self.property = newValue // Retain cycle!!!!
        }

Into this:

        signal.subscribe(with: self) { (observer, newValue) in
            observer.property = newValue
        }

acecilia avatar Jun 29 '18 16:06 acecilia

This would work and some might prefer it, but I do like the bare bones closure approach. This would work even better if you could name observer as "self", overriding the instance reference complectly in the closure, so that one would not have any way of accidentally capturing the actual instance.

artman avatar Jun 30 '18 08:06 artman

@artman rebinding of self is coming in Swift 4.2 I believe: https://github.com/apple/swift/pull/15306

Would you accept this functionality I mentioned in the library? If yes, I may invest some time and look into it.

acecilia avatar Jun 30 '18 13:06 acecilia

For sure!

artman avatar Jul 05 '18 16:07 artman

Hey there, first thanks a lot for this library, pretty neat and useful!

I'm wondering if there's any plans to implement passing the observer to the callback closure? Thanks!

spinach avatar Mar 04 '19 14:03 spinach

It is not in my scope at the moment :/

acecilia avatar Mar 04 '19 14:03 acecilia