Версия 1 > с использованием ObservableObject + @Published
Код: Выделить всё
actor ArticlesService {
func fetchTitle() async throws -> String {
// Simulate a real network call
try await Task.sleep(nanoseconds: 200_000_000)
return "Latest headline"
}
}
final class ViewModel: ObservableObject {
private let service = ArticlesService()
@Published var title = "Loading..."
func refresh() async {
// Hop into the actor for work, then resume here
title = (try? await service.fetchTitle()) ?? "Error"
// ⚠️ ^ Runtime warning appears:
// "Publishing changes from background threads is not allowed; make sure to publish values from the main thread (via operators like receive(on:)) on model updates."
}
}
struct ContentView: View {
@StateObject var vm = ViewModel()
var body: some View {
Text(vm.title)
.task { await vm.refresh() }
}
}
actor ArticlesService {
func fetchTitle() async throws -> String {
try await Task.sleep(nanoseconds: 200_000_000)
return "Latest headline"
}
}
@Observable
final class ViewModel {
private let service = ArticlesService()
var title = "Loading..."
func refresh() async {
title = (try? await service.fetchTitle()) ?? "Error"
//
}
}
struct ContentView: View {
@State var vm = ViewModel()
var body: some View {
Text(vm.title)
.task { await vm.refresh() }
}
}
< /code>
Логика такая же (тот же актер, та же сеть), но версия Combine показывает предупреждение, а версия наблюдения - нет. Почему?
@ObServable автоматически направляется на главного актера? < /P>
Подробнее здесь: https://stackoverflow.com/questions/797 ... eads-is-no
Мобильная версия