Hi, I want to periodically check data from an API. For this purpose, I created a task that runs at regular intervals. However, when I checked the Swift Concurrency Instrument, I saw that it's in the continuation channel. Is this normal behavior when use sleep in tasks?
func startUpdateTask() {
cancelAllTasks()
updateTask = Task {
do {
while !Task.isCancelled {
do {
try await fetchAPIInfo()
try await Task.sleep(nanoseconds: 30_000_000_000)
} catch is CancellationError {
print("Task cancelled")
break
} catch {
print("Error: \(error.localizedDescription)")
try await Task.sleep(nanoseconds: 2_000_000_000)
}
}
} catch {
print("Error: \(error.localizedDescription)")
}
print("Task ended")
}
}
func fetchAPIInfo() async throws {
do {
try Task.checkCancellation()
let newState = await APIService.getAPIInfo()
if case .stateAPISuccess(let newAPIInfo) = newState {
if case .stateAPISuccess(let currentAPIInfo) = currentState, newAPIInfo == currentAPIInfo {
return
}
}
await MainActor.run {
currentState = newState
}
} catch is CancellationError {
print("Task cancelled")
} catch {
print("Error: \(error.localizedDescription)")
}
}
func cancelAllTasks() {
updateTask?.cancel()
updateTask = nil
}