1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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)
}
}
}