Closure (Task) with weak self still keeping self alive?

I've got a class that schedules an "auto save" when a document is modified. I noticed that when the user closed the document, this closure below was keeping the object alive, even though I used weak self. If I use other Task.sleep line instead, the behavior changes - it does not keep the object alive.

Is that the expected behavior? It surprised me. I'm also surprised it lets me reference autoSaveInterval (an instance variable on self) without the self?. prefix. Is this because it's "sendable" - it's doing something different?

autoSaveTask = Task { [weak self] in            
    // await Task.sleep(seconds: self?.autoSaveInterval ?? 15)
    await Task.sleep(seconds: autoSaveInterval)            
    guard let s = self else { return }
    if Task.isCancelled { return }
    await s.save(type: .autoSave)
}
Terms of Service

Privacy Policy

Cookie Policy