只读取 CurrentValueSubject?

Ger*_*eri 3 swift combine

有没有办法创建CurrentValueSubject只读的?

所以你可以sink公开它,value公开阅读,但只能send在内部/私下对其进行评估。想在库模块中使用它。

LuL*_*aGa 6

最好的模式是将其声明为私有:

private let _status = CurrentValueSubject<ThisStatus?, Never>(nil)
Run Code Online (Sandbox Code Playgroud)

并通过计算属性公开它:

public var status: AnyPublisher<ThisStatus?, Never> {
    _status
        .eraseToAnyPublisher()
}
Run Code Online (Sandbox Code Playgroud)

  • 抱歉,我的意思是 [`CurrentValueSubject.value`](https://developer.apple.com/documentation/combine/currentvaluesubject/value)。当您需要初始化值时尤其要注意。 (6认同)