Entdecken Sie einen @Published Var aus einem Schauspielerprotokoll in Swift 6IOS

Programmierung für iOS
Anonymous
 Entdecken Sie einen @Published Var aus einem Schauspielerprotokoll in Swift 6

Post by Anonymous »

Ich möchte auf die Änderungen (zum Beispiel eines Booleschen) Werts eines meiner Schauspieler anhören.

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)

}
Da wir einen @published -Werte in einem Protokoll nicht aufdecken können, habe ich die Publisher -Version oben verwendet.

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
Und dieses für den Kombinat Ansatz:

Code: Select all

Actor-isolated property 'myValuePublisher' can not be referenced from the main actor
Weil Publisher nicht sendbar ist, funktioniert es nicht mit Swift 6. Wie kann ich diesen Wert veröffentlichen? Ist AsyncSequence < /code> jetzt mit Swift 6 oder etwas nur mit Swift 6, oder fehlt mir etwas? : Anscheinend sollte ich keinen Verlag entlarven, da er für Swift 6 nicht bereit ist (und wahrscheinlich nie so sein wird, wie @sweeeper vorschlägt)
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)
}
}
}
}

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post