Update store with fetched posts by setting hasNewerRemoteCopy flag

This commit is contained in:
Angelo Stavrow 2020-08-27 17:41:13 -04:00
parent 201cc27162
commit 5c08a9e723
No known key found for this signature in database
GPG Key ID: 1A49C7064E060EEE
2 changed files with 29 additions and 3 deletions

View File

@ -26,3 +26,24 @@ struct PostStore {
print("local copy not found")
}
}
mutating func updateStore(with fetchedPosts: [Post]) {
for fetchedPost in fetchedPosts {
// Find the local copy in the store.
let localCopy = posts.first(where: { $0.wfPost.postId == fetchedPost.wfPost.postId })
// If there's a local copy, check which is newer; if not, add the fetched post to the store.
if let localCopy = localCopy {
// We do not discard the local copy; we simply set the hasNewerRemoteCopy flag accordingly.
if let remoteCopyUpdatedDate = fetchedPost.wfPost.updatedDate,
let localCopyUpdatedDate = localCopy.wfPost.updatedDate {
localCopy.hasNewerRemoteCopy = remoteCopyUpdatedDate > localCopyUpdatedDate
} else {
print("Error: could not determine which copy of post is newer")
}
} else {
add(fetchedPost)
}
}
}
}

View File

@ -176,6 +176,7 @@ private extension WriteFreelyModel {
func fetchUserPostsHandler(result: Result<[WFPost], Error>) {
do {
let fetchedPosts = try result.get()
var fetchedPostsArray: [Post] = []
for fetchedPost in fetchedPosts {
var post: Post
if let matchingAlias = fetchedPost.collectionAlias {
@ -186,9 +187,13 @@ private extension WriteFreelyModel {
} else {
post = Post(wfPost: fetchedPost)
}
DispatchQueue.main.async {
self.store.add(post)
}
fetchedPostsArray.append(post)
// DispatchQueue.main.async {
// self.store.add(post)
// }
}
DispatchQueue.main.async {
self.store.updateStore(with: fetchedPostsArray)
}
} catch {
print(error)