使用Swift Combine创建Timer Publisher [英] Create a Timer Publisher using Swift Combine

查看:333
本文介绍了使用Swift Combine创建Timer Publisher的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在观看通过SwiftUI WWDC进行数据流讨论.他们有一张带有示例代码的幻灯片,在其中使用了Timer发布者,该发布者连接到SwiftUI视图,并随时间更新UI.

I've been watching the Data Flow Through SwiftUI WWDC talk. They have a slide with a sample code where they use a Timer publisher that gets connected to a SwiftUI View, and updates the UI with the time.

我正在编写一些代码,在其中我想做完全相同的事情,但无法弄清楚该PodcastPlayer.currentTimePublisher的实现方式,然后将其连接到UI结构.我还看了所有关于Combine的视频.

I'm working on some code where I want to do the exact same thing, but can't figure out how this PodcastPlayer.currentTimePublisher is implemented, and then hooked to the UI struct. I have also watched all the videos about Combine.

我该如何实现?

示例代码:

struct PlayerView : View {
  let episode: Episode
  @State private var isPlaying: Bool = true
  @State private var currentTime: TimeInterval = 0.0

  var body: some View {
    VStack { // ...
      Text("\(playhead, formatter: currentTimeFormatter)")
    }
    .onReceive(PodcastPlayer.currentTimePublisher) { newCurrentTime in
      self.currentTime = newCurrentTime
    }
  }
}

推荐答案

在这里,您有一个Combine计时器的示例.我使用的是全局变量,但是您当然应该使用适用于您的方案的任何变量(environmentObject,State等).

Here you have an example of a Combine timer. I am using a global, but of course you should use whatever is applicable to your scenario (environmentObject, State, etc).

import SwiftUI
import Combine

class MyTimer {
    let currentTimePublisher = Timer.TimerPublisher(interval: 1.0, runLoop: .main, mode: .default)
    let cancellable: AnyCancellable?

    init() {
        self.cancellable = currentTimePublisher.connect() as? AnyCancellable
    }

    deinit {
        self.cancellable?.cancel()
    }
}

let timer = MyTimer()

struct Clock : View {
  @State private var currentTime: Date = Date()

  var body: some View {
    VStack {
      Text("\(currentTime)")
    }
    .onReceive(timer.currentTimePublisher) { newCurrentTime in
      self.currentTime = newCurrentTime
    }
  }
}

这篇关于使用Swift Combine创建Timer Publisher的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆