import Foundation import SwiftUI extension AppModel { func loadPost(id: String) async { guard !Task.isCancelled, !isSigningOut else { return } if let pending = postLoadTasks[id], pending.generation == contentGeneration { await pending.task.value return } let request = UUID() let task = Task { await self.loadPostContents(id: id) } postLoadTasks[id] = PostLoadTask(id: request, generation: contentGeneration, task: task) await task.value if postLoadTasks[id]?.id == request { postLoadTasks[id] = nil } } func loadPostContents(id: String) async { guard !Task.isCancelled, !deletedPostIDs.contains(id), loadingPostIDs.insert(id).inserted else { return } let request = UUID() postRequests[id] = request let generation = contentGeneration failedPostIDs.remove(id) postErrors[id] = nil isLoadingPost = true defer { if postRequests[id] == request { postRequests[id] = nil loadingPostIDs.remove(id) isLoadingPost = !loadingPostIDs.isEmpty } } do { let result = try await service.loadThread(uri: id) guard !Task.isCancelled else { return } guard generation == contentGeneration, postRequests[id] == request else { if postRequests[id] == request { failedPostIDs.insert(id) postErrors[id] = "The post changed while it loaded. Try again." } return } let loadedPosts = result.posts.filter { !deletedPostIDs.contains($0.id) }.map(excludingDeletedQuote) withContentUpdates { applyMutedPostIDs(result.mutedPostIDs) if !loadedPosts.contains(where: { $0.id == id }) { removePost(id: id) } updatePosts(loadedPosts, appending: loadedPosts) if threadContexts[id] != loadedPosts { threadContexts[id] = loadedPosts } let positions = result.positions.filter { !deletedPostIDs.contains($0.key) } threadPositions[id] = positions.isEmpty ? nil : positions } if !loadedPosts.contains(where: { $0.id == id }) { failedPostIDs.insert(id) postErrors[id] = "The post is not available. Try opening it again." } } catch { guard generation == contentGeneration, postRequests[id] == request, !Task.isCancelled, !NetworkFailure.isCancellation(error) else { return } failedPostIDs.insert(id) postErrors[id] = NetworkFailure.message(for: error) } } }