Hello I am sorry it's me again :)
I have new questions on async/await and actor
I have my actor that look like this, really simple
actor MyActor {
var value: Int = 0
}
so if I try to modify my value from a closure I need to do like this:
actor MyActor {
var value: Int = 0
func test_withClosureAndTaskAndModifyMyValue() {
let closure: (Int) -> () = { value in
Task {
self.value = 1 // Work
self.update(2) // Work
}
}
}
func update(_ value :Int) {
self.value = value
}
}
for me the task catch the current actor and it will be updated on the actor, So far, so good.
now if my closure is Sendable
self.value = 1
don't work anymore
and
self.update(2)
need to be await
so I am not able to update my value unless I use a method
actor MyActor {
var value: Int = 0
func test_withClosureAndTaskAndModifyMyValue() {
let closure: @Sendable (Int) -> () = { value in
Task {
self.value = 1 // ERROR Actor-isolated property 'value' can not be mutated from a nonisolated context
await self.update(2) // Work
}
}
}
func update(_ value :Int) {
self.value = value
}
}
Ia am asking why but I have something even stranger.
I implemented some code without any real purpose, just to test the limits and try to more undersand
here I don't need to have await anymore for update method
actor MyActor {
var value: Int = 0
lazy var stream = AsyncStream<Int>() { continuation in
continuation.onTermination = { _ in
Task {
self.value = 2 // ERROR Actor-isolated property 'value' can not be mutated from a nonisolated context
self.update(1) // run and not need await anymore
}
}
}
func update(_ value :Int) {
self.value = value
}
}
and even weirdest
I can run task on mainActor it's work without to have await
actor MyActor {
var value: Int = 0
lazy var stream = AsyncStream<Int>() { continuation in
continuation.onTermination = { _ in
Task {@MainActor in
print("") //Main Actor
self.value = 2 // ERROR Actor-isolated property 'value' can not be mutated from a nonisolated context
self.update(1) // run and will be switch on actor and no need await
}
}
}
func update(_ value :Int) {
self.value = value
}
}
If some one can explain me plase :'(