【備忘録】Property WrapperとRxSwift


@propertyWrapper
struct BehaviorRelayWrapper<T> {
    private let relay: BehaviorRelay<T>
    private let observable: Observable<T>
    init(value: T) {
        relay = BehaviorRelay(value: value)
        observable = relay.asObservable()
    }
    var wrappedValue: Observable<T> {
        observable
    }
    var projectedValue: BehaviorRelay<T> {
        relay
    }
}
@propertyWrapper
struct PublishRelayWrapper<T> {
    private let relay: PublishRelay<T>
    private let observable: Observable<T>
    init() {
        relay = PublishRelay<T>()
        observable = relay.asObservable()
    }
    var wrappedValue: Observable<T> {
        observable
    }
    var projectedValue: PublishRelay<T> {
        relay
    }
}
@propertyWrapper
struct AnyObserverWrapper<T> {
    private let relay = PublishRelay<T>()
    private let observer: AnyObserver<T>
    private let observable: Observable<T>
    init() {
        observer = .create(relay)
        observable = relay.asObservable()
    }
    var wrappedValue: AnyObserver<T> {
        observer
    }
    var projectedValue: Observable<T> {
        observable
    }
}

RxSwiftでのViewModelの記述をシンプルにすることができる。
参考にさせていただきました。
https://gist.github.com/sgr-ksmt/2cc92d8c7d517e08767fbe296b6da720

※AnyObserverはリンク先のextensionが必要になります