I've worked out a solution - it's taken my way too long: I feel daft looking back on my first clumsy attempt.
Two of my key mistakes were to put the my RecordViewModel object (which needed to conform to ObservableObject) on the MainActor, and to create an actor type, RecordsModel, to hold the property that the needed to be isolated.
Here's the original attempt:
actor RecordsModel: Decodable {
var records: [Record] = []
enum CodingKeys: String, CodingKey { case records }
init() {}
init(from decoder: Decoder) async throws { ... }
// Unable to conform to Encodable at present with this implementation
func encode(to encoder: Encoder) throws { ... }
func addRecord() -> [Record] {
self.records.append(Record(value: Int.random(in: 0...10))) // Assume it takes a long time to compute `value`
return self.records
}
}
@MainActor
class RecordsViewModel: ObservableObject {
@Published var records: [Record]
private let recordsModel: RecordsModel
init() {
self.records = []
self.recordsModel = RecordsModel()
}
init(fromRecordsModel recordsModel: RecordsModel) async {
self.records = await recordsModel.records
self.recordsModel = recordsModel
}
func addRecord() {
// Given addRecord takes time to complete, we run it in the background
Task {
self.records = await recordsModel.addRecord()
}
}
}
My new approach doesn't create an actor, but puts a property isolatedRecords in the view model, isolated with a global actor. This is complimented by a non-isolated published version, which is updated on the MainActor after any updates to its isolated twin.
Here's the new view model class:
final class Records: ObservableObject, Codable {
@Published var records: [Record]
@MyActor private var isolatedRecords: [Record]
init() {
self.records = []
self.isolatedRecords = []
}
enum CodingKeys: String, CodingKey { case records }
init(from decoder: Decoder) throws { ... }
func encode(to encoder: Encoder) throws { ... }
@MyActor func append(_ value: Int) -> [Record] {
self.isolatedRecords.append(Record(value))
return isolatedRecords
}
func addRecord() {
Task() {
let newNumber = Int.random(in: 0...10) // Assume lots of processing here, hence we run it as a Task
let newRecords = await self.append(newNumber)
await MainActor.run { self.records = newRecords }
}
}
}
This has succeeded in ensuring the code is free of race-conditions, whilst keeping processing and update syncronisation of the record's array off the main thread, and removing all the other issues I encountered such as trying to conform the actor to Encodable, putting the Document on the MainActor and more. The code is more elegant also.
I've left the full updated project at GitHub