RxProperty

一个只读的 BehaviorRelay,它(几乎)等同于 ReactiveSwiftProperty

此类对于在 ViewModel 内部封装 BehaviorRelay 非常有用,这样其他类就无法访问其 setter(不可绑定),从而使状态管理更安全。

简而言之

public final class 💩ViewModel<T> {
    // 💩 This is almost the same as `var state: T`.
    // DON'T EXPOSE VARIABLE!
    public let state = BehaviorRelay<T>(...)

    // 💩 Exposing `Observable` is NOT a good solution either
    // because type doesn't tell us that it contains at least one value
    // and we cannot even "extract" it.
    public var stateObservable: Observable<T> {
        return state.asObservable()
    }
}
public final class 👍ViewModel<T> {
    // 👍 Hide variable.
    private let _state = BehaviorRelay<T>(...)

    // 👍 `Property` is a better type than `Observable`.
    public let state: Property<T>
    
    public init() {
        self.state = Property(_state)
    }
}

免责声明

由于此库应该直接进入 RxSwift-core,所以没有计划作为第三方微框架发布到 CocoaPods/Carthage /SwiftPackageManager

(Swift Package Manager 在 inamiy/RxProperty#5 中得到支持)

如果您喜欢它,请赞同 ReactiveX/RxSwift#1118 并加入讨论。目前推荐的方法是将源代码直接添加到您的项目中。

许可证

MIT