@@ -13,22 +13,28 @@ public final actor WorldService: APIService, WorldServiceProtocol {
13
13
public let client : APIClient
14
14
private let path = " worlds "
15
15
private let limit = 100
16
+ private let maxCount = 400
17
+ private typealias FavoriteWorldsWithOffset = ( offset: Int , worlds: [ FavoriteWorld ] )
16
18
17
19
public func fetchWorld( worldId: String ) async throws -> World {
18
20
let response = try await client. request ( path: " \( path) / \( worldId) " , method: . get)
19
21
return try await Serializer . shared. decode ( response. data)
20
22
}
21
23
22
24
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 }
30
37
}
31
- return Array ( allFavorites)
32
38
}
33
39
34
40
private func fetchFavoritedWorlds( n: Int , offset: Int ) async throws -> [ FavoriteWorld ] {
0 commit comments