UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

@Published value incorrect on first render

Forums > Swift

I have a @Published variable that gets updated in a view model once a network request has completed. I do this to ensure everything has finished loading before the user can interact with the a button on the page. However, the published variable in the view model does not reflect correctly in the view until after the user has interacted with the page then it behaves as expected. How can I ensure the correct value is there on page load? I will paste an example below

View Model - I have essentially cleared all the code expect the variable that is not updating correctly. isCartCalculated. This is the variable that is false in the model even though it is set to true in the view model. Thanks for any insight!

import Combine
import SwiftUI

class CheckoutViewModel: ObservableObject {
    @Published var isCartCalculated: Bool = false

    func calculateCart(for address: Address? = nil) {
        if (cart.items.isEmpty) {
            return
        }

        let onCompletion: ((Subscribers.Completion<ApiError>) -> Void) =  { completion in
            switch completion {
            case .failure(let error):

                }
            case .finished:
                self.isCartCalculated = true
                break
            }
        }

        ApiService.calculateCart(for: cart, shippingAddress: address)
            .receive(on: DispatchQueue.main)
            .sink(receiveCompletion: onCompletion, receiveValue: onValue)
            .store(in: &disposables)
    }
}

View


import Combine
import CoreData
import SwiftUI
import Stripe

struct Checkout: View {
    @ObservedObject var viewModel: CheckoutViewModel

    var isPayButtonDisabled: Bool {
        let hasAddressIfRequired = self.viewModel.cart.getFulfillmentMethod() == .shipping ? userStore.selectedAddress != nil : true
        let hasPaymentMethod = self.paymentContextDelegate.paymentMethodButtonTitle != "Select a Payment"
        print("pay button")
        print(viewModel.isCartCalculated)

        return (requiresPayment() && !hasPaymentMethod) || !hasAddressIfRequired || viewModel.hasError || userStore.salesTax == nil || viewModel.isCartCalculated == false
    }

    init(viewModel: CheckoutViewModel) {
        self.viewModel = viewModel
    }

    func onAppear() {
        self.viewModel.calculateCart()
    }

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.