下記コードの self.message = "OK"
と self.message = "NG"
のところで以下のエラーが発生します。
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.
ViewModel:
import Foundation
import Combine
import Network
class ContentViewModel: ObservableObject {
@Published var message = ""
private let monitor = NWPathMonitor()
private let queue = DispatchQueue(label: "network_monitor")
init() {
monitor.pathUpdateHandler = { path in
if path.status == .satisfied {
self.message = "OK"
} else {
self.message = "NG"
}
}
monitor.start(queue: queue)
}
}
View:
import SwiftUI
struct ContentView: View {
@ObservedObject var contentViewModel = ContentViewModel()
var body: some View {
VStack {
Text(self.contentViewModel.message)
}.frame(
maxWidth: .infinity,
maxHeight: .infinity
)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
警告を回避し、メインスレッドで動かすのであれば
if path.status == .satisfied {
DispatchQueue.main.async {
self.message = "OK"
}
} else {
DispatchQueue.main.async {
self.message = "NG"
}
}
と DispatchQueue.main.async
で囲めば解決しますが、警告には via operators like receive(on:)
といってるので receive(on:)
を使う書き方があるのでしょうか? そしてそれはどのように書くのでしょうか?