Skip to content

Commit b373963

Browse files
committed
feat: implement fetching all favorites in FavoriteSerivce, sort by offset
1 parent 7cfffab commit b373963

File tree

2 files changed

+15
-9
lines changed

2 files changed

+15
-9
lines changed

Sources/VRCKit/Services/FavoriteService.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ public final actor FavoriteService: APIService, FavoriteServiceProtocol {
2727
try await withThrowingTaskGroup(of: [Favorite].self) { taskGroup in
2828
for offset in [0, 100, 200, 300] {
2929
taskGroup.addTask { [unowned self] in
30-
try await self.listFavorites(n: 100, offset: offset, type: type)
30+
try await listFavorites(n: 100, offset: offset, type: type)
3131
}
3232
}
3333
var results: [Favorite] = []

Sources/VRCKit/Services/WorldService.swift

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,22 +13,28 @@ public final actor WorldService: APIService, WorldServiceProtocol {
1313
public let client: APIClient
1414
private let path = "worlds"
1515
private let limit = 100
16+
private let maxCount = 400
17+
private typealias FavoriteWorldsWithOffset = (offset: Int, worlds: [FavoriteWorld])
1618

1719
public func fetchWorld(worldId: String) async throws -> World {
1820
let response = try await client.request(path: "\(path)/\(worldId)", method: .get)
1921
return try await Serializer.shared.decode(response.data)
2022
}
2123

2224
public func fetchFavoritedWorlds() async throws -> [FavoriteWorld] {
23-
var allFavorites = Set<FavoriteWorld>()
24-
var offset = 0
25-
while true {
26-
let batch = try await fetchFavoritedWorlds(n: limit, offset: offset)
27-
allFavorites.formUnion(batch)
28-
if batch.count < limit { break }
29-
offset += limit
25+
try await withThrowingTaskGroup(of: FavoriteWorldsWithOffset.self) { taskGroup in
26+
for offset in Array(stride(from: 0, to: maxCount, by: limit)) {
27+
taskGroup.addTask { [unowned self] in
28+
let worlds = try await fetchFavoritedWorlds(n: limit, offset: offset)
29+
return (offset, worlds)
30+
}
31+
}
32+
var resultsDict: [FavoriteWorldsWithOffset] = []
33+
for try await result in taskGroup { resultsDict.append(result) }
34+
return resultsDict
35+
.sorted { $0.offset < $1.offset }
36+
.flatMap { $0.worlds }
3037
}
31-
return Array(allFavorites)
3238
}
3339

3440
private func fetchFavoritedWorlds(n: Int, offset: Int) async throws -> [FavoriteWorld] {

0 commit comments

Comments
 (0)