RxCocoa에서는 Cocoa 프레임워크를 사용할떄 rx 네임스페이스를 이용하여 Rx방식으로 사용할 수 있도록 지원한다.

스크린샷 2024-06-25 오후 3.43.01.png

UILable에 rx 네임스페이스를 붙히면 Reactive<UILabel> 속성이 된다.

Reactive.swift

@dynamicMemberLookup
public struct Reactive<Base> {
    /// Base object to extend.
    public let base: Base

    /// Creates extensions with base object.
    ///
    /// - parameter base: Base object.
    public init(_ base: Base) {
        self.base = base
    }

    /// Automatically synthesized binder for a key path between the reactive
    /// base and one of its properties
    public subscript<Property>(dynamicMember keyPath: ReferenceWritableKeyPath<Base, Property>) -> Binder<Property> where Base: AnyObject {
        Binder(self.base) { base, value in
            base[keyPath: keyPath] = value
        }
    }
}

Reactive는 구조체로 이루어져있고 Base 속성을 제네릭 타입으로 받는다.(UILabel이 Base 타입)

@dynamicMemberLookup은 런타임시 dot synstax를 가능하게 하는 attribute이다. 런타임시 다이나믹한 속성을 받아서 Cocoa프레임워크 UI와 RxCocoa의 기능을 연결해주는? 역할이라고 이해를 했다.

/// A type that has reactive extensions.
public protocol ReactiveCompatible {
    /// Extended type
    associatedtype ReactiveBase

    /// Reactive extensions.
    static var rx: Reactive<ReactiveBase>.Type { get set }

    /// Reactive extensions.
    var rx: Reactive<ReactiveBase> { get set }
}

다음으로 ReactiveCompatible 이라는 프로토콜이 존재하는데 해당 프로토콜이 rx라는 네임스페이스를 사용하는것과 연관이 있는것같다. rx 네임스페이스는 Reactive<ReactiveBase>를 리턴한다.

extension ReactiveCompatible {
    /// Reactive extensions.
    public static var rx: Reactive<Self>.Type {
        get { Reactive<Self>.self }
        // this enables using Reactive to "mutate" base type
        // swiftlint:disable:next unused_setter_value
        set { }
    }

    /// Reactive extensions.
    public var rx: Reactive<Self> {
        get { Reactive(self) }
        // this enables using Reactive to "mutate" base object
        // swiftlint:disable:next unused_setter_value
        set { }
    }
}

ReactiveCompatible의 실제 구현체이다. Reactive(self) 를 리턴한다. Reactive를 적용한 어떠한 인스턴스를 리턴하는 의미이다.

extension NSObject: ReactiveCompatible { }

그 어떠한 인스턴스는 NSObject를 상속한 모든 클래스를 의미한다.

NSObject는 Cocoa 프레임워크 UI의 루트클래스이다. 모든 UI가 ReactiveCompatible의 기본구현을 가지게 된다.

정리

NSObject를 상속받은 클래스는 ReactiveCompatible를 자동으로 채택 → .rx 네임스페이스 사용 → Reactive기능이 바인딩된 클래스를 리턴(Reactive(UILabel)