[英]How to assign sink result to variable
I would like to assign a result form a notification center publisher to the variable alert
.我想将通知中心发布者的结果表单分配给变量
alert
。 The Error that I get is:我得到的错误是:
Cannot use instance member 'alerts' within property initializer; property initializers run before 'self' is available
Could Someone help me out here?有人可以帮我吗?
import Foundation
import SwiftUI
import Combine
final class PublicAlerts: ObservableObject{
init () {
fetchAlerts()
}
var alerts = [String](){
didSet {
didChange.send(self)
}
}
private func fetchPublicAssets(){
backEndService().fetchAlerts()
}
let publicAssetsPublisher = NotificationCenter.default.publisher(for: .kPublicAlertsNotification)
.map { notification in
return notification.userInfo?["alerts"] as! Array<String>
}.sink {result in
alerts = result
}
let didChange = PassthroughSubject<PublicAlerts, Never>()
}
Later I will use alerts
this in SwiftUI as a List稍后我将在 SwiftUI 中使用
alerts
作为列表
Move the subscribtion in init在init中移动订阅
final class PublicAlerts: ObservableObject{
var anyCancelable: AnyCancellable? = nil
init () {
anyCancelable = NotificationCenter.default.publisher(for: .kPublicAlertsNotification)
.map { notification in
return notification.userInfo?["alerts"] as! Array<String>
}.sink {result in
alerts = result
}
fetchAlerts()
}
var alerts = [String](){
didSet {
didChange.send(self)
}
}
private func fetchPublicAssets(){
backEndService().fetchAlerts()
}
let didChange = PassthroughSubject<PublicAlerts, Never>()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.