Even slight main thread congestion causes Alert to miss dismissals

One frequent but hard to reproduce bug in SwiftUI is being unable to dismiss a basic Alert. I think I've managed to reproduce the issue here. If there is even a little congestion in the main thread, here in the form of a counter the updates every 0.1 seconds, the Alert will fail to dismiss 90% of the time. This level of activity should be nothing remarkable. It will dismiss sometimes but usually does not. See attached project.

Feedback case: https://feedbackassistant.apple.com/feedback/14719229
Answered by VAndrJ in 799725022

For this sample project just move out the counter Text to standalone View and pass Binding:

struct CounterView: View {
    @Binding var counter: Int

    var body: some View {
        Text("Counter: \(counter)")
            .font(.caption)
    }
}

Then replace this:

Text("Counter: \(counter)")
    .font(.caption)

With:

CounterView(counter: $counter)

P.S. To understand the problem, add in the body:

var body: some View {
    let _ = Self._printChanges()
    ...

For this sample project just move out the counter Text to standalone View and pass Binding:

struct CounterView: View {
    @Binding var counter: Int

    var body: some View {
        Text("Counter: \(counter)")
            .font(.caption)
    }
}

Then replace this:

Text("Counter: \(counter)")
    .font(.caption)

With:

CounterView(counter: $counter)

P.S. To understand the problem, add in the body:

var body: some View {
    let _ = Self._printChanges()
    ...

You're missing the point, the problem isn't with the counter, that was just to demonstrate the problem with Alert.

It only happens with that particular Alert modifier, with other ones it works fine.

Accepted Answer

You are right, it is just a workaround for this particular case, allowing to avoid constant calls to the body and Alert reinitializations.

It turns out that when calling body, when reinitializing Alert, the connection with the AlertController, which is displayed, is somehow lost. Which leads to this problem.

But it is unlikely that we need to wait for this problem fixes, since Alert is deprecated.

Even slight main thread congestion causes Alert to miss dismissals
 
 
Q