Code: Select all
protocol MyServiceProtocol: Actor {
var myValuePublisher: Published.Publisher { get }
}
actor MyService: MyServiceProtocol {
@Published private(set) var myValue = false
var myValuePublisher: Published.Publisher { $myValue }
// ... (modifies myValue)
}
Code: Select all
@MainActor
final class MyViewModel {
private let myService: MyServiceProtocol = MyService()
func testMyService() {
// Accessing myValuePublisher as an async stream
Task {
for await newValue in await myService.myValuePublisher.values {
print("New value :", newValue)
}
}
// OR
// Accessing myValuePublisher with Combine
let cancellable = await myService.myValuePublisher.sink { value in
print("New value :", newValue)
}
}
}
< /code>
, aber ich erhalte diesen Kompilierungsfehler für die Verwendung von Async Stream: < /p>
Non-sendable type 'Published.Publisher' of property 'myValuePublisher' cannot exit actor-isolated context
Code: Select all
Actor-isolated property 'myValuePublisher' can not be referenced from the main actor
Also hier ist mein Versuch mit einem asyncstream :
Code: Select all
protocol MyServiceProtocol: Actor {
var myValue: Bool { get }
func myValueStream() -> AsyncStream
}
actor MyService: MyServiceProtocol {
private(set) var myValue = false
private var myValueContinuation: AsyncStream.Continuation?
deinit {
myValueContinuation?.finish() // Not sure if needed
}
private func modifyValue() {
myValue = true
myValueContinuation?.yield(true)
}
public func myValueStream() -> AsyncStream {
AsyncStream { continuation in
myValueContinuation = continuation
continuation.yield(myValue)
}
}
}
@MainActor
final class MyViewModel {
private let myService: MyServiceProtocol = MyService()
func testMyService() {
Task {
for await newValue in await myService.myValueStream() {
print("New value: ", newValue)
}
}
}
}