Swift Combine:在可观察对象中使用计时器发布者

时间:2019-09-04 23:59:19

标签: swift xcode swiftui xcode11 combine

在这个问题被标记为this other question的重复项之前,我试图了解发布者如何以我所期望的方式工作。

使用与前面提到的问题的答案相同的示例:

// Let's define the view model with my view...
import Combine
import SwiftUI

class TimerViewModel: ObservableObject {
  private let cancellable: AnyCancellable?

  let intervalPublisher = Timer.TimerPublisher(
                            interval: 1.0, 
                            runLoop: .main, 
                            mode: .default)

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

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

struct Clock : View {
  @EnvironmentObject var viewModel: TimerViewModel
  @State private var currentTime: String = "Initial"


  var body: some View {
    VStack {
      Text(currentTime)
    }
    .onReceive(timer.intervalPublisher) { newTime in
      self.currentTime = String(describing: newTime)
    }
  }
}

在这个阶段,我要做的就是我的视图模型直接发布值。我不需要声明视图将接收这些类型的值。

理想情况下,我想将发布者正确地发布为...尽管我可以使用以下代码:

// Let's define the view model with my view...
import Combine
import SwiftUI

class TimerViewModel: ObservableObject {
  private let cancellable: AnyCancellable?
  private let assignCancellable: AnyCancellable?

  let intervalPublisher = Timer.TimerPublisher(
                            interval: 1.0, 
                            runLoop: .main, 
                            mode: .default)
 @Published var tick: String = "0:0:0"

  init() {
    cancellable = intervalPublisher.connect() as? AnyCancellable

    assignCancellable = intervalPublisher
                              .map { new in String(describing: new) }
                              .assign(to: \TimerViewModel.tick, on: self)
  }

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

struct Clock : View {
  @EnvironmentObject var viewModel: TimerViewModel
  @State private var currentTime: String = "Initial"


  var body: some View {
    VStack {
      Text(currentTime)
      Text(viewModel.tick) // why doesn't this work?
    }
    .onReceive(timer.intervalPublisher) { newTime in
      self.currentTime = String(describing: newTime)
    }
  }
}

assign我在做什么错了?

为什么不触发?

编辑:创建“时钟”视图后,就在SceneDelegate上设置了环境对象。排除的代码附在下面:

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).

        // Create the SwiftUI view that provides the window contents.
        let view = Clock().environmentObject(TimerViewModel())

        // Use a UIHostingController as window root view controller.
        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            window.rootViewController = UIHostingController(rootView: view)
            self.window = window
            window.makeKeyAndVisible()
        }
    }

3 个答案:

答案 0 :(得分:3)

这与您的原始图片有些不同,但我希望没有什么重要的改变。

import Combine
import SwiftUI

class TimerViewModel: ObservableObject {
    private var assignCancellable: AnyCancellable? = nil

    @Published var tick: String = "0:0:0"

    init() {
        assignCancellable = Timer.publish(every: 1.0, on: .main, in: .default)
            .autoconnect()
            .map { String(describing: $0) }
            .assign(to: \TimerViewModel.tick, on: self)
    }
}


struct ContentView: View {
    @State private var currentTime: String = "Initial"
    @ObservedObject var viewModel = TimerViewModel()

    var body: some View {
        VStack {
            Text(currentTime)
            Text(viewModel.tick) // why doesn't this work?
        }
        .onReceive(Timer.publish(every: 0.9, on: .main, in: .default).autoconnect(),
                perform: {
                    self.currentTime = String(describing: $0)
                }
        )
    }
}

我将viewModel设为ObservedObject只是为了简化代码。

Timer.publish方法与自动连接一起使Timer易于使用。我发现使用具有多个订阅者的同一发布者会导致问题,因为第一个取消操作会杀死发布者。

我删除了deinit(),因为取消似乎对订户是隐含的。

onReceive和viewModel的更新之间存在干扰,但是将onReceive更改为0.9可以解决此问题。

最后,我发现Combine中的print()方法对于监视管道非常有用。

答案 1 :(得分:0)

“ @ EnvironmentObject”必须在祖先视图上设置模型对象。

我没看到这个。

所以,我确实重写了您的代码。

import SwiftUI
import Combine

struct ContentView: View {
    let timer = TimerViewModel()
    var body: some View {
        VStack {
            Text("Hello World")
            TimerView().environmentObject(timer)
        }
    }
}

struct TimerView: View {
    @EnvironmentObject var timer: TimerViewModel

    var body: some View {
        Text(timer.time)
    }
}

class TimerViewModel: ObservableObject {
    @Published var time = "init"

    private let innerTimer = Timer.TimerPublisher(interval: 1.0, runLoop: .main, mode: .default)
    private let cancellable: Cancellable
    private var anyCancellable: AnyCancellable?

    init() {
        cancellable = innerTimer.connect()
        anyCancellable = innerTimer
            .map({ $0.description })
            .assign(to: \TimerViewModel.time, on: self)
    }

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

答案 2 :(得分:0)

首先尝试Text("Timer: \(date, style:.timer)"),它会自动为您提供一个计数计时器。

还要考虑Timer.publisher的优点,因为它返回可以存储在@State中的结构,因此您甚至不需要ObservableObject

import Combine
import SwiftUI

struct Clock : View {
  @State private var timer = Timer.publish(every: 1, on: .main, in:.common).autoconnect()
  @State private var currentTime: String = "Initial"

  var body: some View {
    VStack {
      Text(currentTime)
    }
    .onReceive(timer) { newTime in
      self.currentTime = String(describing: newTime)
    }
  }
}

Timer设置为@State的好处是,如果由于某种原因不再显示时钟,则计时器将停止并被丢弃。

但是,如果您确实决定使用ObservableObject,则只需执行以下操作:

class MyTimer : ObservableObject {
    var objectWillChange = Timer.publish(every: 1, on: .main, in:.common).autoconnect()
}

struct Clock2: View {
    @StateObject var timer = MyTimer() // causes body to run every second
    var body: some View {
        VStack {
            Text("Hello, World! \(Date())")
        }
    }
}

这是另一种对日期字符串进行更准确更改的方法:

class MyTimer : ObservableObject {
    var timer : Timer? = nil
    @Published var timeString = ""

    init() {
        timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in
            self.timeString = timer.fireDate.description
        }
    }
}

struct ContentView: View {
    @StateObject var timer = MyTimer()

    var body: some View {
        VStack {
            Text("Hello, World! \(timer.timeString)")
        }
    }
}