Post

Replies

Boosts

Views

Activity

I think there's a logic error in Apple SwiftUI tutorial Scrumdinger.
Hi. In Apple's SwiftUI Tutorial Scrumdinger, there's a logic that read and save a file in asynchronous function to keep the App's UI responsive. The tutorial says, Reading from the file system can be slow. To keep the interface responsive, you’ll write an asynchronous function to load data from the file system. Making the function asynchronous lets the system efficiently prioritize updating the user interface instead of sitting idle and waiting while the file system reads data. And here's code. @MainActor class ScrumStore: ObservableObject { @Published var scrums: [DailyScrum] = [] func load() async throws { let task = Task<[DailyScrum], Error> { let fileURL = try Self.fileURL() guard let data = try? Data(contentsOf: fileURL) else { return [] } let dailyScrums = try JSONDecoder().decode([DailyScrum].self, from: data) return dailyScrums } let scrums = try await task.value } func save(scrums: [DailyScrum]) async throws { let task = Task { let data = try JSONEncoder().encode(scrums) let outfile = try Self.fileURL() try data.write(to: outfile) } _ = try await task.value } } But the problem i think here is that the ScrumStore is Mainactor isolated annotated, the 'load' and 'save' method execute their Tasks in the main thread, so I think there's not much benefit we can get comparing using a synchronous method. The proper way I think here is that use 'Task.detached' initializer instead of 'Task' initializer, so that the Task doesn't isolated in MainActor context. If there's anything I understand wrong or miss, please let me know. Apple's Scrumdinger Tutorial Link
1
0
492
Aug ’23