Section 12/161 menit
12. Migrasi dari Combine
12. Migrasi dari Combine
Jika project sudah menggunakan Combine dan ingin bertahap migrasi ke Async Algorithms:
Konversi Publisher ke AsyncSequence
swift
// Bridge Combine Publisher ke AsyncSequence
import Combine
import AsyncAlgorithms
extension Publisher where Failure == Never {
var asyncStream: AsyncStream<Output> {
AsyncStream { continuation in
let cancellable = sink { completion in
continuation.finish()
} receiveValue: { value in
continuation.yield(value)
}
continuation.onTermination = { _ in
cancellable.cancel()
}
}
}
}
extension Publisher {
var asyncThrowingStream: AsyncThrowingStream<Output, Error> {
AsyncThrowingStream { continuation in
let cancellable = sink { completion in
switch completion {
case .finished: continuation.finish()
case .failure(let error): continuation.finish(throwing: error)
}
} receiveValue: { value in
continuation.yield(value)
}
continuation.onTermination = { _ in
cancellable.cancel()
}
}
}
}
// Penggunaan: Combine Publisher dipakai sebagai AsyncSequence
let publisher = NotificationCenter.default
.publisher(for: UIApplication.didBecomeActiveNotification)
Task {
for await _ in publisher.asyncStream {
await refreshData()
}
}
Perbandingan Operator
| Combine | Async Algorithms | Catatan |
|---|---|---|
debounce(for:scheduler:) |
.debounce(for:clock:) |
Clock menggantikan Scheduler |
throttle(for:scheduler:latest:) |
.throttle(for:clock:reducing:) |
reducing lebih fleksibel |
combineLatest(_:) |
combineLatest(_:) |
Hampir sama |
zip(_:) |
zip(_:) |
Sama |
merge(with:) |
merge(_:) |
Sama |
scan(_:_:) |
.reductions(_:_:) |
Sama semantics |
removeDuplicates() |
.removeDuplicates() |
Sama |
collect() |
chunks(ofCount:) |
Berbeda: async collect tidak ada equivalent langsung |
flatMap |
.flatMap |
Ada di Swift stdlib untuk AsyncSequence |
retry(_:) |
(tidak ada built-in) | Implementasi manual |
catch(_:) |
(tidak ada built-in) | Tangkap di dalam for-loop |