SwiftUI Realm @Published property

Viewed 114

I have the following class:

class User: ObservableObject {
    @Published private(set) var isPremium: Bool = false
    @Published private var subscriptionType: String = "Trial"
    
    private var cancellables = [AnyCancellable]()
    
    init() {
        $subscriptionType
            .map { type in
                if (type == "Trial" || type == "Subscription_3m") {
                    return true
                }
                return false
            }
            .assign(to: \.isPremium, on: self)
            .store(in: &cancellables)
    }
}

Now, I would like to be able to persist this user in a Realm DB. So the class would look something like this:

class User: Object {
    @Published private(set) var isPremium: Bool = false
    @Persisted private var subscriptionType: String = "Trial"
    
    private var cancellables = [AnyCancellable]()
    
    override init() {
        super.init()
        
        $subscriptionType
            .map { type in
                if (type == "Trial" || type == "Subscription_3m") {
                    return true
                }
                return false
            }
            .assign(to: \.isPremium, on: self)
            .store(in: &cancellables)
    }
}

The problem I'm facing is that the $ notation of the subscriptionType property is no longer valid now that the property is wrapped as @Persisted i.s.o @Published

How can I observe changes to subscriptionType like in the original user to be able to change the value of isPremium when a change comes through?

1 Answers

You could try ditching the Combine approach all together and use a classic approach with a setter method:

@Persisted private var subscriptionType: String = "Trial"{
        didSet{
            if (subscriptionType == "Trial" || subscriptionType == "Subscription_3m") {
                isPremium = true
            }
            isPremium = false
        }
    }
Related