WIP: deferred sync

This commit is contained in:
Jackson Harper 2022-12-23 14:55:31 +08:00
parent 4298183a24
commit e23cb722fc
3 changed files with 20 additions and 8 deletions

View file

@ -79,7 +79,9 @@ import Views
let thresholdIndex = items.index(items.endIndex, offsetBy: -5)
// Check if user has scrolled to the last five items in the list
if let itemIndex = itemIndex, itemIndex > thresholdIndex, items.count < thresholdIndex + 10 {
// Make sure we aren't currently loading though, as this would get triggered when the first set
// of items are presented to the user.
if let itemIndex = itemIndex, itemIndex > thresholdIndex, items.count < thresholdIndex + 10, !isLoading {
await loadItems(dataService: dataService, audioController: audioController, isRefresh: false)
}
}
@ -104,14 +106,15 @@ import Views
}
}
func syncItems(dataService: DataService, syncStartTime: Date) async {
func syncItems(dataService: DataService, syncStartTime _: Date) async {
let lastSyncDate = dateFormatter.date(from: dataService.lastItemSyncTime) ?? Date(timeIntervalSinceReferenceDate: 0)
let syncResult = try? await dataService.syncLinkedItems(since: lastSyncDate,
cursor: nil,
deferFetchingMore: true)
if syncResult != nil {
dataService.lastItemSyncTime = dateFormatter.string(from: syncStartTime)
if syncResult?.hasMore {
// dataService.lastItemSyncTime = dateFormatter.string(from: syncStartTime)
self.isLoading = true
}
// If possible start prefetching new pages in the background

View file

@ -15,10 +15,12 @@ public struct LinkedItemQueryResult {
public struct LinkedItemSyncResult {
public let updatedItemIDs: [String]
public let cursor: String?
public let hasMore: Bool
public init(updatedItemIDs: [String], cursor: String?) {
public init(updatedItemIDs: [String], cursor: String?, hasMore: Bool) {
self.updatedItemIDs = updatedItemIDs
self.cursor = cursor
self.hasMore = hasMore
}
}

View file

@ -34,17 +34,19 @@ public extension DataService {
let prev = previousQueryResult?.updatedItemIDs ?? []
let result = LinkedItemSyncResult(
updatedItemIDs: prev + fetchResult.items.map(\.id),
cursor: fetchResult.cursor
cursor: fetchResult.cursor,
hasMore: fetchResult.hasMoreItems
)
if fetchResult.hasMoreItems, (previousQueryResult?.updatedItemIDs.count ?? 0) < 40 {
print("synced since:", date, "total synced items:", result.updatedItemIDs.count, ", fetchResult.hasMoreItems", fetchResult.hasMoreItems)
if fetchResult.hasMoreItems {
if deferFetchingMore {
Task.detached(priority: .background) {
try await self.syncLinkedItems(
since: date,
cursor: fetchResult.cursor,
previousQueryResult: result,
deferFetchingMore: deferFetchingMore
deferFetchingMore: false
)
}
} else {
@ -55,6 +57,11 @@ public extension DataService {
deferFetchingMore: deferFetchingMore
)
}
} else {
print("setting last synced time to: ", date)
DispatchQueue.main.async {
self.lastItemSyncTime = DateFormatter.formatterISO8601.string(from: date)
}
}
return result