Async Sequences क्या हैं
एक async sequence एक regular list जैसा है जिसे आप loop करते हैं, सिवाय इसके कि हर item को आने में थोड़ा समय लग सकता है, एक समय में एक।
Syntax
for await element in asyncSequence {
// runs each time an element arrives
}
var results: [Type] = []
for await element in asyncSequence {
results.append(element)
}
Iterating an Async Sequence with for await
एक AsyncSequence के elements for await से consume किए जाते हैं, जो हर element के available होने के बीच suspend होता है।
उदाहरण: Iterating an Async Sequence with for await
struct Countdown: AsyncSequence {
typealias Element = Int
let start: Int
struct AsyncIterator: AsyncIteratorProtocol {
var current: Int
mutating func next() async -> Int? {
guard current > 0 else { return nil }
defer { current -= 1 }
return current
}
}
func makeAsyncIterator() -> AsyncIterator {
return AsyncIterator(current: start)
}
}
for await number in Countdown(start: 3) {
print(number)
}
Login to try C/C++/Java/PHP code in the editor
Collecting Async Sequence Results
एक async sequence से produce हुई values को for await loop के अंदर हर element append करके एक regular array में collect किया जा सकता है।
उदाहरण: Collecting Async Sequence Results
struct Countdown: AsyncSequence {
typealias Element = Int
let start: Int
struct AsyncIterator: AsyncIteratorProtocol {
var current: Int
mutating func next() async -> Int? {
guard current > 0 else { return nil }
defer { current -= 1 }
return current
}
}
func makeAsyncIterator() -> AsyncIterator {
return AsyncIterator(current: start)
}
}
var collected: [Int] = []
for await number in Countdown(start: 4) {
collected.append(number)
}
print(collected)
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- एक
AsyncSequenceको एक plainfor-inloop से iterate करने की कोशिश करना; इसके बजाय इसेfor awaitचाहिए। - यह भूल जाना कि एक custom async sequence को
AsyncIteratorProtocolकेnext()method को एकasyncfunction के रूप में implement करना चाहिए। - यह मान लेना कि एक async sequence अपनी सभी values instantly deliver करता है; हर element genuinely उनके बीच एक delay के साथ produce हो सकता है।
चैप्टर सारांश
AsyncSequenceएक sequence describe करता है जिसके elements asynchronously, एक समय में एक produce होते हैं।- एक को iterate करने के लिए
for await element in sequenceचाहिए। - एक custom async sequence
AsyncIteratorProtocolको एकasync func next()के साथ implement करता है। - Async sequences data की streams के लिए उपयोगी हैं जो incrementally आती हैं, जैसे live updates।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: