7

I want to keep firing a function 5 seconds after it completes.

Previously I would use this at the end of the function:

Timer.scheduledTimer(withTimeInterval: 5, repeats: false) { self.function() }

But I am wanting to use Swift 5.5's async/await.

If I use something like this:

func loadInfo() async {
    async let info = someOtherAsyncFunc()
    self.info = try? await info
    await Task.sleep(5_000_000_000)
    await loadInfo()
}

I get a warning that the Function call causes an infinite recursion and it's not really cancellable.

This compiles fine:

func loadInfo() async {
    Task {
        async let info = someOtherAsyncFunc()
        self.info = try? await info
        await Task.sleep(5_000_000_000)
        if Task.isCancelled {
            print("Cancelled")
        }
        else
        {
            print("Not cancelled")
            await loadInfo()
        }
    }
}

and although it does fire every 5 seconds, it keeps running when my SwiftUI view is dismissed. I start it using:

.onAppear {
    loadInfo()
}

As it's all running on the same Task and not detached should it not all cancel when the view is removed?

What is the modern way to achieve this with async/await?

George
  • 25,988
  • 10
  • 79
  • 133
Darren
  • 10,182
  • 20
  • 95
  • 162

2 Answers2

6

You can save the task in a @State variable, and then cancel it when the view disappears with onDisappear(perform:).

Working example:

struct ContentView: View {
    @State private var info: String?
    @State private var currentTask: Task<Void, Never>?

    var body: some View {
        NavigationView {
            VStack {
                Text(info ?? "None (yet)")
                    .onAppear(perform: loadInfo)
                    .onDisappear(perform: cancelTask)

                NavigationLink("Other view") {
                    Text("Some other view")
                }
            }
            .navigationTitle("Task Test")
        }
        .navigationViewStyle(.stack)
    }

    private func loadInfo() {
        currentTask = Task {
            async let info = someOtherAsyncFunc()
            self.info = try? await info
            await Task.sleep(5_000_000_000)
            guard !Task.isCancelled else { return }
            loadInfo()
        }
    }

    private func cancelTask() {
        print("Disappear")
        currentTask?.cancel()
    }

    private func someOtherAsyncFunc() async throws -> String {
        print("someOtherAsyncFunc ran")
        return "Random number: \(Int.random(in: 1 ... 100))"
    }
}
George
  • 25,988
  • 10
  • 79
  • 133
  • 1
    Thanks, this is great. I had to make a slight modification to make it compile. I need to use `.onAppear` instead of `.task` as the `loadInfo()` function is not `async`. – Darren Aug 12 '21 at 07:27
  • 1
    @Darren Thank you, I've now changed it. For me it compiled with `.task(_:)` on Xcode 13b3, but not Xcode 13b5. – George Aug 12 '21 at 07:50
2

The point of async await is to let you write asynchronous code in a synchronous way. So you could remove the recursive function and simply write:

.task {
    repeat {
        // code you want to repeat
        print("Tick")

        try? await Task.sleep(for: .seconds(5)) // exception thrown when cancelled by SwiftUI when this view disappears.
    } while (!Task.isCancelled)
    print("Cancelled")  
}

I noticed the print tick is always on main thread however if I move it out to its own async func then it correctly runs on different threads.

malhal
  • 26,330
  • 7
  • 115
  • 133