# Using the MainActor to manage access to mutable state

**URL:** <https://forums.swift.org/t/using-the-mainactor-to-manage-access-to-mutable-state/71961>\
**Category:** Using Swift\
**Tags:** concurrency\
**Created:** [May 20, 2024, 6:33pm UTC](https://forums.swift.org/t/using-the-mainactor-to-manage-access-to-mutable-state/71961 "2024-05-20T18:33:58Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![phildow](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/phildow/32/31361_2.png) [@phildow](https://forums.swift.org/u/phildow)\
**Post date:** [May 20, 2024, 6:33pm UTC](https://forums.swift.org/t/using-the-mainactor-to-manage-access-to-mutable-state/71961/1 "2024-05-20T18:33:58Z")

</div>

I am updating the build settings in a project to Targeted Strict Concurrency Checking and am seeing warnings with a design pattern that we use frequently. The pattern involves a ViewModel with view-driving Published properties isolated to the MainActor and an asynchronous function called off the MainActor that needs both to access and update those properties:

```swift
class ViewModel: ObservableObject {
    @MainActor @Published private(set) var value: Int = 0
    
    func process(data: Int) async {
        let newValue = await value + data
        await MainActor.run {
            value = newValue
        }
    }
}

```

The compiler gives me the following two warnings:

1. On the `await value`: Non-sendable type 'ViewModel' passed in implicitly asynchronous call to main actor-isolated property 'value' cannot cross actor boundary
2. In the `await MainActor.run` closure: Capture of 'self' with non-sendable type 'ViewModel' in a `@Sendable` closure

I can address these warnings by adding `@unchecked Sendable` conformance to the ViewModel, and I'd like to ask here if I am addressing the Sendable requirement correctly by doing so.

According to the docs "Reference types that internally manage access to their state" are sendable. When I use the MainActor to manage access to the `value` property, I am exactly doing this, right?

My question: is there a problem using the MainActor to manage access to mutable state like this, especially when that state already needs to be isolated to the MainActor since it drives UI, and is there some other way I should be doing this?

A couple alternatives I've considered:

1. Isolate the entire ViewModel to the MainActor
2. Separate out the `process` method into some other object, probably an actor

I can't isolate the entire ViewModel to the MainActor because I need the potentially long-running `process` method to execute off the MainActor. Separating out the `process` method to another object is an option, but I end up duplicating many of the properties (eg `value`) and still have to coordinate between the two objects. This just seems like extra effort that is unnecessary if using the MainActor to manage access to mutable state is appropriate.

---

<div class="post-metadata">

**Author:** ![vns](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/vns/32/37396_2.png) [@vns](https://forums.swift.org/u/vns)\
**Post date:** [May 20, 2024, 6:45pm UTC](https://forums.swift.org/t/using-the-mainactor-to-manage-access-to-mutable-state/71961/2 "2024-05-20T18:45:04Z")

</div>

It is kinda official recommendation from Apple to annotate type as whole to be `@MainActor` isolated. So in general you’d better make whole view model to run on main actor (which is reasonable since this is a _view_ model). It will also greatly simplify the code.

> [@phildow](#):
>
> I can't isolate the entire ViewModel to the MainActor because I need the potentially long-running `process` method to execute off the MainActor.

Move out this long running process to one of these things:

- nonisolated function inside view model
- separate nonisolated type (might be tricky)
- separate actor

Which will address the issue of only the thing that should not be on main actor will be called from other isolation, plus better separation of the code.

---

<div class="post-metadata">

**Author:** ![phildow](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/phildow/32/31361_2.png) [@phildow](https://forums.swift.org/u/phildow)\
**Post date:** [May 20, 2024, 6:50pm UTC](https://forums.swift.org/t/using-the-mainactor-to-manage-access-to-mutable-state/71961/3 "2024-05-20T18:50:52Z")

</div>

Thanks for the quick response. Using a nonisolated function sounds like my best option.

---

<div class="post-metadata">

**Author:** ![nkbelov](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/nkbelov/32/34617_2.png) [@nkbelov](https://forums.swift.org/u/nkbelov)\
**Post date:** [May 21, 2024, 8:40am UTC](https://forums.swift.org/t/using-the-mainactor-to-manage-access-to-mutable-state/71961/4 "2024-05-21T08:40:57Z")

</div>

Another option is spawning an internal detached task and awaiting its value:

```swift
@MainActor // or the whole class
func process(data: Int) async {
    let input = self.value // access synchronously on main actor
    let newValue = await Task.detached {
       // runs on the global executor
       return doLongRunningStuff(input)
    }.value

   self.value = newValue // write synchronously on main actor
}

```

The detached task will not clog up the main actor, and you will be getting the benefits of reading and writing the input/output synchronously, which helps with reasoning about transactionality of the operation. Although if you only read and write arguments and return values, a `nonisolated` function works just fine.

You can also simply move the function out of the type; global `async` functions are nonisolated by definition.

---

<div class="post-metadata">

**Author:** ![vns](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/vns/32/37396_2.png) [@vns](https://forums.swift.org/u/vns)\
**Post date:** [May 21, 2024, 9:07am UTC](https://forums.swift.org/t/using-the-mainactor-to-manage-access-to-mutable-state/71961/5 "2024-05-21T09:07:59Z")

</div>

I’d better avoid introducing unstructured concurrency as much as possible. Especially when it can efficiently be represented as nonisolated function.

---

<div class="post-metadata">

**Author:** ![hisekaldma](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/hisekaldma/32/1146_2.png) [@hisekaldma](https://forums.swift.org/u/hisekaldma)\
**Post date:** [May 22, 2024, 5:29am UTC](https://forums.swift.org/t/using-the-mainactor-to-manage-access-to-mutable-state/71961/6 "2024-05-22T05:29:42Z")

</div>

> [@phildow](#):
>
> ```swift
> let newValue = await value + data
> await MainActor.run {
> value = newValue
> }
> 
> ```

I don’t know what processing you’re actually doing, but this looks like a race condition to me. If `value` is updated between the first and second line, you will overwrite that value on the third line. And if you call `process` multiple times concurrently, there’s no guarantee that the last one to read from `value` will be the last one to write to `value`.

---

<div class="post-metadata">

**Author:** ![phildow](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/phildow/32/31361_2.png) [@phildow](https://forums.swift.org/u/phildow)\
**Post date:** [May 30, 2024, 5:15pm UTC](https://forums.swift.org/t/using-the-mainactor-to-manage-access-to-mutable-state/71961/7 "2024-05-30T17:15:46Z")

</div>

Yes in our case we guarantee that process is called serially.
