Modern Concurrency: Getting Started

Oct 18 2022 Swift 5.5, iOS 15, Xcode 13.4

Part 2: Asynchronous Sequences

15. Using Combine

Episode complete

Play next episode

Next
Save for later
About this episode
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 14. Canceling Tasks Next episode: 16. Concurrent Downloads

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.

Make sure the course server is running and continue with your project from the previous episode or open the starter project for this episode.

Using Combine: Timer

In this episode, you’ll add a timer, to show how long a download is taking. You’ll use Apple’s Timer class, which is much easier to use, now that it has a Combine publisher.

import Combine
@State var timerTask: Task<Void, Error>?
@State var downloadTask: Task<Void, Error>? 🟩{
  didSet {
    
  }
}
timerTask?.cancel()
guard isDownloadActive else { return }
let startTime = Date().timeIntervalSince1970
let timerSequence = Timer
  .publish(every: 1, on: .main, in: .common)
let timerSequence = Timer
  .publish(every: 1, tolerance: 1, on: .main, in: .common)
  🟩
  .autoconnect()
let timerSequence = Timer
  .publish(every: 1, tolerance: 1, on: .main, in: .common)
  .autoconnect()
  🟩
  .map { date -> String in
    let duration = Int(date.timeIntervalSince1970 - startTime)
    return "\(duration)s"
  }
let timerSequence = Timer
  .publish(every: 1, tolerance: 1, on: .main, in: .common)
  .autoconnect()
  .map { date -> String in
    let duration = Int(date.timeIntervalSince1970 - startTime)
    return "\(duration)s"
  }
  🟩
  .values
timerTask = Task {
  for await duration in timerSequence {
    self.duration = duration
  }
}
timerTask?.cancel()
timerTask?.cancel()