Search code examples
swiftswiftuinsnotificationcentercombine

How to assign sink result to variable


I would like to assign a result form a notification center publisher to the variable 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


Solution

  • Move the subscribtion in 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>()
    }