Skip to content

Commit

Permalink
improvement: utilize TaskGroup when retrieving assets
Browse files Browse the repository at this point in the history
  • Loading branch information
colealanroberts committed Jan 23, 2023
1 parent 36604e2 commit 82b6ce8
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 16 deletions.
31 changes: 20 additions & 11 deletions Sources/OpenAlpha/Internal/Models/Media.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//
// Media.swift
//
//
//
// Created by Cole Roberts on 12/28/22.
//
Expand Down Expand Up @@ -42,17 +42,26 @@ public final class Media: FetchableSize {
}

func fetch(sizes: [Size]) async throws {
for size in sizes {
switch size {
case .thumbnail:
try await thumbnail?.fetch()
case .small:
try await small?.fetch()
case .large:
try await large?.fetch()
case .original:
try await original?.fetch()
let thumbnail: Asset? = self.thumbnail
let small: Asset? = self.small
let large: Asset? = self.large
let original: Asset? = self.original

try await withThrowingTaskGroup(of: Void.self) { group in
for size in sizes {
switch size {
case .thumbnail:
group.addTask { try await thumbnail?.fetch() }
case .small:
group.addTask { try await small?.fetch() }
case .large:
group.addTask { try await large?.fetch() }
case .original:
group.addTask { try await original?.fetch() }
}
}

try await group.waitForAll()
}
}
}
Expand Down
18 changes: 13 additions & 5 deletions Sources/OpenAlpha/Internal/Providers/MediaProvider.swift
Original file line number Diff line number Diff line change
Expand Up @@ -47,15 +47,23 @@ final class MediaProvider: MediaProviding {
let result = try await ResultXMLParser(data: response).parse()
let items = try await ItemXMLParser(result).parse()
let media = items.compactMap(Media.init)

for item in media {
try await item.fetch(sizes: sizes)
}

try await fetch(media, with: sizes)
_ = try await DLNA.EndAction(ip: ip).request(with: session)
return media
} catch {
throw error
}
}

// MARK: - `Private Methods` -

private func fetch(_ media: [Media], with sizes: [Media.Size]) async throws {
return try await withThrowingTaskGroup(of: Void.self) { group in
for medium in media {
group.addTask { try await medium.fetch(sizes: sizes) }
}

return try await group.waitForAll()
}
}
}

0 comments on commit 82b6ce8

Please sign in to comment.