Sunday, December 15, 2024
HomeiOS Developmentios - Concurrency points with HKLiveWorkoutBuilder managed by @Observable class

ios – Concurrency points with HKLiveWorkoutBuilder managed by @Observable class


The issue is that builder and session are remoted to the MainActor however not Sendable. You can’t name nonisolated async strategies on it as a result of that may find yourself sending it off the principle actor.

You must name beginCollection in a non-isolated methodology, so there aren’t any actor hops that sends non-sendable values. You must solely assign the builder and session again to the occasion properties (sending them again to the principle actor) after you’re accomplished with them. Because of region-based isolation, Swift understands that that is your final time utilizing the builder and session within the non-isolated methodology, so they’re protected to be despatched off.

When you ship them again to the principle actor earlier than that, you’re basically sharing the occasion between the principle actor and the non-isolated code after that, which after all isn’t protected with non-sendable values.

// most important actor remoted model so as to simply name from a view
func startWatchWorkout(_ title: String, _ startDate: Date) async {
    await startWatchWorkoutImpl(title, startDate)
}

personal nonisolated func startWatchWorkoutImpl(_ title: String, _ startDate: Date) async {
    do {
        let configuration = HKWorkoutConfiguration()
        configuration.activityType = .traditionalStrengthTraining
        // be aware that I'm not assigning to self.session and self.builder right here
        let session = strive HKWorkoutSession.make(healthStore: retailer, configuration: configuration)
        let builder = session?.associatedWorkoutBuilder()
        builder?.dataSource = HKLiveWorkoutDataSource(healthStore: retailer, workoutConfiguration: configuration)
        session?.startActivity(with: startDate)
        strive await builder?.beginCollection(at: startDate)
        await setSessionAndBuilder(session, builder)
    } catch {
        // ...
    }
}

// assigning the properties ought to be accomplished in a most important actor remoted context
personal func setSessionAndBuilder(_ s: HKWorkoutSession?, _ b: HKLiveWorkoutBuilder?) {
    session = s
    builder = b
}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments