gpt4 book ai didi

ios - 单例中的@Published 属性在第一个事件之后不发出事件

转载 作者:行者123 更新时间:2023-11-28 23:21:36 25 4
gpt4 key购买 nike

我在单例类中有一个 @Published 属性,它在 View 模型类中被观察到,它只收到第一个初始值,而不是之后。为什么?

查看

import SwiftUI

struct ContentView: View {

@ObservedObject var viewModel = ContentViewModel(singletonService: SingletonService.shared)

var body: some View {
NavigationView {
Form {
Text("Hello World")
}.navigationBarItems(trailing: Button("Increase Number", action: {
SingletonService.shared.increaseNumber()
}))
}
}
}

View 模型

import Combine

class ContentViewModel: ObservableObject {

init(
singletonService: SingletonService
) {
let cencellable = singletonService.$number.sink(receiveValue: { print($0) })
// Never called after the first time
}

}

单例

import Combine

class SingletonService {

static let shared = SingletonService()

@Published var number = 0

func increaseNumber() {
number += 1
}

}

最佳答案

订阅一直存在,直到订阅者还活着,但在这种情况下

let cencellable = singletonService.$number.sink(receiveValue: { print($0) 

订阅者被断章取义。应该是这样的

private var cancellables = Set<AnyCancellable>()

init(singletonService: SingletonService) {
singletonService.$number
.sink(receiveValue: { print($0) })
.store(in: &cancellables)
}

关于ios - 单例中的@Published 属性在第一个事件之后不发出事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59593765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com