Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/0xleif/forkedarraypicturesexample
Example of calling an async function for every element in the array, in parallel. Examples include TaskGroup and ForkedArray from Fork.
https://github.com/0xleif/forkedarraypicturesexample
async-await swift
Last synced: 8 days ago
JSON representation
Example of calling an async function for every element in the array, in parallel. Examples include TaskGroup and ForkedArray from Fork.
- Host: GitHub
- URL: https://github.com/0xleif/forkedarraypicturesexample
- Owner: 0xLeif
- Created: 2022-08-27T19:22:30.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2022-08-27T19:24:27.000Z (over 2 years ago)
- Last Synced: 2024-10-31T04:11:57.530Z (about 2 months ago)
- Topics: async-await, swift
- Language: Swift
- Homepage: https://github.com/0xLeif/Fork
- Size: 6.84 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Fork ForkedArray Pictures Example
```swift
import Fork
import SwiftUIclass PicsumImageStore: ObservableObject {
@Published var images: [UIImage] = []
// TaskGroup
func fetch(urls: [URL]) async throws {
await withThrowingTaskGroup(of: Void.self) { taskGroup in
for url in urls {
taskGroup.addTask {
try await self.fetch(url: url)
}
}
}
}
// ForkedArray
func forkFetch(urls: [URL]) async throws {
try await urls.asyncForEach(fetch(url:))
}
private func fetch(url: URL) async throws {
let (data, _) = try await URLSession.shared.data(from: url)
guard let image = UIImage(data: data) else { return }
DispatchQueue.main.async {
self.images.append(image)
}
}
}struct ContentView: View {
private let imageURLs: [URL] = (1 ... 100).compactMap { URL(string: "https://picsum.photos/id/\($0)/200/300") }
@StateObject var imageStore = PicsumImageStore()
var body: some View {
if imageStore.images.isEmpty {
Button("Fetch Images") {
Task {
/*
// Using Swift TaskGroup
try! await imageStore.fetch(urls: imageURLs)
*/
// Using ForkedArray
try! await imageStore.forkFetch(urls: imageURLs)
}
}
} else {
List(imageStore.images, id: \.self) { image in
Image(uiImage: image)
}
}
}
}
```