Search code examples
iosswiftrx-swiftrx-cocoa

Make Observable for UIButton isHighlighted property


I'm trying to create isHighlighted Observable for my UIButton, to send sequence every time isHiglighted for UIButton has changed. And I've write something like this

extension Reactive where Base: UIButton {

    var isHighlighted: Observable<Bool> {

        let property = self.base.rx.controlProperty(editingEvents: .allTouchEvents,
                                                    getter: { _ in self.base.isHighlighted },
                                                    setter: { (_, _) in })
        return property
            .distinctUntilChanged()
            .asObservable()
    }
}

The problem is, that it doesn't work for .touchUpInside. If I drag finger outside UIButton and then come back, it works fine, but not for tap action. I think immediately after .touchUpInside it's still highlighted for very short time.


Solution

  • Thanks @iWheelBuy I've created code that works, without RxOptional, I based it partially on your answer so Thank you! Here is working code:

    extension Reactive where Base: UIButton {
        var isHighlighted: Observable<Bool> {
            let anyObservable = self.base.rx.methodInvoked(#selector(setter: self.base.isHighlighted))
    
            let boolObservable = anyObservable
                .flatMap { Observable.from(optional: $0.first as? Bool) }
                .startWith(self.base.isHighlighted)
                .distinctUntilChanged()
                .share()
    
            return boolObservable
        }
    }