Is the following code accurate/safe?
final class ObjectWithPublished: @unchecked Sendable {
@Published
var property: Int?
}
I've tried testing this with the following test, which passes:
final class PublishedThreadSafetyTests: XCTestCase {
func testSettingValueFromMultipleThreads() {
let object = ObjectWithPublished()
let iterations = 1000
let completesIterationExpectation = expectation(description: "Completes iterations")
completesIterationExpectation.expectedFulfillmentCount = iterations
let receivesNewValueExpectation = expectation(description: "Received new value")
receivesNewValueExpectation.expectedFulfillmentCount = iterations
var cancellables: Set<AnyCancellable> = []
object
.$property
.dropFirst()
.sink { _ in
receivesNewValueExpectation.fulfill()
}
.store(in: &cancellables)
DispatchQueue.concurrentPerform(iterations: iterations) { iteration in
object.property = iteration
completesIterationExpectation.fulfill()
}
waitForExpectations(timeout: 1)
}
}
There are also no warnings when using the address sanitizer, so it seems like subscriptions and updating @Published
values is thread-safe, but the Published
type is not marked Sendable
so I can't be 100% sure.
If this isn't safe, what do I need to protect to have the Sendable
conformance be correct?