我有一个接收器,需要在收到第一个值后立即取消。我不关心未来的值,只关心第一个发布的值。因为如果不存储AnyCancelable由接收器创建的,垃圾收集器将删除该接收器,所以我必须存储它。同时,我也必须在sink完成后清理它,否则,我会出现内存泄漏。
我使用 UUID \xe2\x86\x92 AnyCancelable 映射构建了一个,但我担心这比应有的更复杂;还有另一种方法可以做到这一点吗?联合有什么推荐的?
\n@Published var locationState: (location: CLLocation?, error: Error?)?\nvar requestLocationSinks: [String: AnyCancellable] = [:]\n\n// 1. Generate ID to uniquely identify the current sink.\nlet sinkID = UUID().uuidString\n\n// 2. Start the sink and store it in our ID \xe2\x86\x92 AnyCancellable dictionary.\nrequestLocationSinks[sinkID] = $locationState.sink { locationState in\n if let locationState = locationState {\n invokeCallbackWithLocationState(locationState)\n }\n // 3. Remove the stored AnyCancellable as soon as we received our first value!\n self.requestLocationSinks.removeValue(forKey: sinkID)\n}\nRun Code Online (Sandbox Code Playgroud)\n
如果您只需要保持它的活动状态直到接收器被调用一次,您可以创建一个临时变量
var cancellable: AnyCancellable?
cancellable = $locationState.sink { locationState in
if let locationState = locationState {
invokeCallbackWithLocationState(locationState)
}
cancellable = nil
}
Run Code Online (Sandbox Code Playgroud)
这将保留AnyCancellable足够长的时间(因为闭包保留了引用)
| 归档时间: |
|
| 查看次数: |
7952 次 |
| 最近记录: |