How to ensure non-async portion of async function executes before view assignment?

I have following (simplified) model:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>struct PostDetailResponse: Codable {
var post_detail: PostDetailContent
}
struct PostDetailContent: Codable {
var userHasLiked: Bool?
enum CodingKeys: String, CodingKey {
case userHasLiked = "user_has_liked"
}
}
// Full data structure used within the application
struct PostDetailed {
var userHasLiked: Bool?
}
extension PostDetailed {
mutating func update(with postDetailContent: PostDetailContent) {
self.userHasLiked = postDetailContent.userHasLiked
}
}
</code>
<code>struct PostDetailResponse: Codable { var post_detail: PostDetailContent } struct PostDetailContent: Codable { var userHasLiked: Bool? enum CodingKeys: String, CodingKey { case userHasLiked = "user_has_liked" } } // Full data structure used within the application struct PostDetailed { var userHasLiked: Bool? } extension PostDetailed { mutating func update(with postDetailContent: PostDetailContent) { self.userHasLiked = postDetailContent.userHasLiked } } </code>
struct PostDetailResponse: Codable {
    var post_detail: PostDetailContent
}

struct PostDetailContent: Codable {
    var userHasLiked: Bool?
    enum CodingKeys: String, CodingKey {
        case userHasLiked = "user_has_liked"
    }
}
// Full data structure used within the application
struct PostDetailed {
    var userHasLiked: Bool?
}
extension PostDetailed {
    mutating func update(with postDetailContent: PostDetailContent) {
        self.userHasLiked = postDetailContent.userHasLiked
    }
}

It is populate via selectPost which is defined in the viewmodel:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import Foundation
import SwiftUI
import KeychainAccess
import Kingfisher
class PostDetailedPageViewModel: ObservableObject {
@Published var postDetailed: PostDetailed
@Published var isLoading = false
@Published var errorMessage: String?
init(postDetailed: PostDetailed) {
self.postDetailed = postDetailed
}
func selectPost(postID: String) async {
print("This should happen FIRST")
DispatchQueue.main.async {
self.isLoading = true
}
let keychainHelper = KeychainHelperUtility(service: "com.venividi.app")
do {
guard let accessToken = try keychainHelper.getAccessToken() else {
DispatchQueue.main.async {
self.errorMessage = "Error retrieving access token"
self.isLoading = false
}
return
}
// Using async/await to call the API service
let data = try await APIGetService(token: accessToken).invokeGetUserPostDetailedLambda(postID: postID)
DispatchQueue.main.async {
self.isLoading = false
if let data = data {
self.updatePostDetail(with: data)
} else {
self.errorMessage = "No data received from the server"
}
}
} catch {
DispatchQueue.main.async {
self.isLoading = false
// Adjust error message based on the type of error
if let error = error as? URLError {
self.errorMessage = "Networking error: (error.localizedDescription)"
print(self.errorMessage as Any)
print("we fuckin up")
} else {
self.errorMessage = "Error: (error.localizedDescription)"
print("we fuckin uppp")
}
}
}
}
private func updatePostDetail(with data: Data) {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(DateFormatter.iso8601MilliSeconds)
do {
let jsonResponse = try decoder.decode(PostDetailResponse.self, from: data)
let postDetail = jsonResponse.post_detail
print("we got all of the detail and its here (postDetail)")
DispatchQueue.main.async {
// Update the content and locationsJson directly from the decoded data
self.postDetailed.userHasLiked = postDetail.userHasLiked
print("This should happen SECOND")
}
} catch {
print("there was an issue")
DispatchQueue.main.async {
self.errorMessage = "Failed to decode post details: (error.localizedDescription)"
print(self.errorMessage ?? "Failed")
}
}
}
}
</code>
<code>import Foundation import SwiftUI import KeychainAccess import Kingfisher class PostDetailedPageViewModel: ObservableObject { @Published var postDetailed: PostDetailed @Published var isLoading = false @Published var errorMessage: String? init(postDetailed: PostDetailed) { self.postDetailed = postDetailed } func selectPost(postID: String) async { print("This should happen FIRST") DispatchQueue.main.async { self.isLoading = true } let keychainHelper = KeychainHelperUtility(service: "com.venividi.app") do { guard let accessToken = try keychainHelper.getAccessToken() else { DispatchQueue.main.async { self.errorMessage = "Error retrieving access token" self.isLoading = false } return } // Using async/await to call the API service let data = try await APIGetService(token: accessToken).invokeGetUserPostDetailedLambda(postID: postID) DispatchQueue.main.async { self.isLoading = false if let data = data { self.updatePostDetail(with: data) } else { self.errorMessage = "No data received from the server" } } } catch { DispatchQueue.main.async { self.isLoading = false // Adjust error message based on the type of error if let error = error as? URLError { self.errorMessage = "Networking error: (error.localizedDescription)" print(self.errorMessage as Any) print("we fuckin up") } else { self.errorMessage = "Error: (error.localizedDescription)" print("we fuckin uppp") } } } } private func updatePostDetail(with data: Data) { let decoder = JSONDecoder() decoder.dateDecodingStrategy = .formatted(DateFormatter.iso8601MilliSeconds) do { let jsonResponse = try decoder.decode(PostDetailResponse.self, from: data) let postDetail = jsonResponse.post_detail print("we got all of the detail and its here (postDetail)") DispatchQueue.main.async { // Update the content and locationsJson directly from the decoded data self.postDetailed.userHasLiked = postDetail.userHasLiked print("This should happen SECOND") } } catch { print("there was an issue") DispatchQueue.main.async { self.errorMessage = "Failed to decode post details: (error.localizedDescription)" print(self.errorMessage ?? "Failed") } } } } </code>
import Foundation
import SwiftUI
import KeychainAccess
import Kingfisher
class PostDetailedPageViewModel: ObservableObject {
    
    @Published var postDetailed: PostDetailed
    @Published var isLoading = false
    @Published var errorMessage: String?
    
    init(postDetailed: PostDetailed) {
        self.postDetailed = postDetailed
    }
    
    func selectPost(postID: String) async {
        print("This should happen FIRST")
        DispatchQueue.main.async {
            self.isLoading = true
        }
        
        let keychainHelper = KeychainHelperUtility(service: "com.venividi.app")
        
        do {
            guard let accessToken = try keychainHelper.getAccessToken() else {
                DispatchQueue.main.async {
                    self.errorMessage = "Error retrieving access token"
                    self.isLoading = false
                }
                return
            }
            // Using async/await to call the API service
            let data = try await APIGetService(token: accessToken).invokeGetUserPostDetailedLambda(postID: postID)
            DispatchQueue.main.async {
                self.isLoading = false
                if let data = data {
                    self.updatePostDetail(with: data)
                } else {
                    self.errorMessage = "No data received from the server"
                }
            }
        } catch {
            DispatchQueue.main.async {
                self.isLoading = false
                // Adjust error message based on the type of error
                if let error = error as? URLError {
                    self.errorMessage = "Networking error: (error.localizedDescription)"
                    print(self.errorMessage as Any)
                    print("we fuckin up")
                } else {
                    self.errorMessage = "Error: (error.localizedDescription)"
                    print("we fuckin uppp")
                }
            }
        }
    }
    
    private func updatePostDetail(with data: Data) {
        let decoder = JSONDecoder()
        decoder.dateDecodingStrategy = .formatted(DateFormatter.iso8601MilliSeconds)
        
        do {
            let jsonResponse = try decoder.decode(PostDetailResponse.self, from: data)
            let postDetail = jsonResponse.post_detail
            print("we got all of the detail and its here (postDetail)")
            
            DispatchQueue.main.async {
                // Update the content and locationsJson directly from the decoded data

                self.postDetailed.userHasLiked = postDetail.userHasLiked
                print("This should happen SECOND")

            }
        } catch {
            print("there was an issue")
            DispatchQueue.main.async {
                self.errorMessage = "Failed to decode post details: (error.localizedDescription)"
                print(self.errorMessage ?? "Failed")
            }
        }
    }
}

The view runs the selectPost in .onAppear since this page is navigated to from a list of a variety of posts.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>struct PostDetailedPageView: View {
@StateObject var viewModel: PostDetailedPageViewModel
init(postDetailed: PostDetailed) {
_viewModel = StateObject(wrappedValue: PostDetailedPageViewModel(postDetailed: postDetailed)
}
@State private var isMapExpanded = false
@State private var isLiked = false // State to manage the like button
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 20) {
// Display the number of likes with heart button
HStack {
Button(action: {
isLiked.toggle()
}) {
Image(systemName: isLiked ? "heart.fill" : "heart")
.foregroundColor(isLiked ? .red : .gray)
}
Text("(viewModel.postDetailed.likesCount ?? 0) likes")
.font(.caption)
.foregroundColor(.gray)
}
}
.onAppear {
Task {
await viewModel.selectPost(postID: viewModel.postDetailed.postID)
print("This should happen THIRD (viewModel.postDetailed.userHasLiked ?? nil)")
if let userHasLiked = viewModel.postDetailed.userHasLiked {
DispatchQueue.main.async {
isLiked = userHasLiked
print("isLiked is now set to (isLiked)")
}
} else {
print("userHasLiked is nil")
}
}
}
}
.padding()
.navigationTitle("Post Details")
.navigationBarTitleDisplayMode(.inline)
}
}
</code>
<code>struct PostDetailedPageView: View { @StateObject var viewModel: PostDetailedPageViewModel init(postDetailed: PostDetailed) { _viewModel = StateObject(wrappedValue: PostDetailedPageViewModel(postDetailed: postDetailed) } @State private var isMapExpanded = false @State private var isLiked = false // State to manage the like button var body: some View { ScrollView { VStack(alignment: .leading, spacing: 20) { // Display the number of likes with heart button HStack { Button(action: { isLiked.toggle() }) { Image(systemName: isLiked ? "heart.fill" : "heart") .foregroundColor(isLiked ? .red : .gray) } Text("(viewModel.postDetailed.likesCount ?? 0) likes") .font(.caption) .foregroundColor(.gray) } } .onAppear { Task { await viewModel.selectPost(postID: viewModel.postDetailed.postID) print("This should happen THIRD (viewModel.postDetailed.userHasLiked ?? nil)") if let userHasLiked = viewModel.postDetailed.userHasLiked { DispatchQueue.main.async { isLiked = userHasLiked print("isLiked is now set to (isLiked)") } } else { print("userHasLiked is nil") } } } } .padding() .navigationTitle("Post Details") .navigationBarTitleDisplayMode(.inline) } } </code>
struct PostDetailedPageView: View {

    @StateObject var viewModel: PostDetailedPageViewModel
    
    init(postDetailed: PostDetailed) {
        _viewModel = StateObject(wrappedValue: PostDetailedPageViewModel(postDetailed: postDetailed)
    }
    
    @State private var isMapExpanded = false
    @State private var isLiked = false  // State to manage the like button

    var body: some View {
        ScrollView {
            VStack(alignment: .leading, spacing: 20) {
                // Display the number of likes with heart button
                HStack {
                    Button(action: {
                        isLiked.toggle()
                        
                    }) {
                        Image(systemName: isLiked ? "heart.fill" : "heart")
                            .foregroundColor(isLiked ? .red : .gray)
                    }
                    Text("(viewModel.postDetailed.likesCount ?? 0) likes")
                        .font(.caption)
                        .foregroundColor(.gray)
                }

            }
            .onAppear {
                Task {
                    await viewModel.selectPost(postID: viewModel.postDetailed.postID)
                    print("This should happen THIRD (viewModel.postDetailed.userHasLiked ?? nil)")
                    if let userHasLiked = viewModel.postDetailed.userHasLiked {
                        DispatchQueue.main.async {
                            isLiked = userHasLiked
                            print("isLiked is now set to (isLiked)")
                        }
                    } else {
                        print("userHasLiked is nil")
                    }
                }
            }
        }
        .padding()
        .navigationTitle("Post Details")
        .navigationBarTitleDisplayMode(.inline)
    }

}

I am expecting the order of operations to follow those described in the print statements:

  1. This should happen FIRST
  2. This should happen SECOND
  3. This should happen THIRD

If this worked in the right order, we would be assigning the view‘s @State private var isLiked to the value properly populated into viewModel.postDetailed.userHasLiked from updatePostDetail. Unfortunately, the order occurs as follows:

  1. This should happen FIRST
  2. This should happen THIRD
  3. This should happen SECOND

This leads to isLiked always being assigned nil. I don’t understand why the isLiked = userHasLiked is running before updatePostDetail has finished executing. The latter is tucked inside of an async function selectPost which we are explicitly saying to await. Why would the isLiked = userHasLiked run before all parts of selectPost – including the nested updatePostDetail – are completed?

How can I ensure this works properly? I have thought to simply use viewModel.postDetailed.userHasLiked directly within the view, but then I lose out on the benefits of using the @State variable in the view and this seems like bad practice.

Note I have ensured that the data is being properly populated and called from the database via invokeGetUserPostDetailedLambda, so you can assume this works properly.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật