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
About this episode

Leave a rating/review

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

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

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()