5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【備忘録】Property WrapperとRxSwift

Last updated at Posted at 2021-03-12
@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が必要になります

5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?