'async/await, Task and [weak self]
Okay so we all know that in traditional concurrency in Swift, if you are performing (for example) a network request inside a class, and in the completion of that request you reference a function that belongs to that class, you must pass [weak self] in, like this:
func performRequest() {
apiClient.performRequest { [weak self] result in
self?.handleResult(result)
}
}
This is to stop us strongly capturing self in the closure and causing unnecessary retention/inadvertently referencing other entities that have dropped out of memory already.
How about in async/await? I'm seeing conflicting things online so I'm just going to post two examples to the community and see what you think about both:
class AsyncClass {
func function1() async {
let result = await performNetworkRequestAsync()
self.printSomething()
}
func function2() {
Task { [weak self] in
let result = await performNetworkRequestAsync()
self?.printSomething()
}
}
func function3() {
apiClient.performRequest { [weak self] result in
self?.printSomething()
}
}
func printSomething() {
print("Something")
}
}
function3 is straightforward - old fashioned concurrency means using [weak self].
function2 I think is right, because we're still capturing things in a closure so we should use [weak self].
function1 is this just handled by Swift, or should I be doing something special here?
Solution 1:[1]
Bottom line, there is often little point in using [weak self] capture lists with Task objects. Use cancelation patterns instead.
A few detailed considerations:
Weak capture lists are not required.
You said:
in traditional concurrency in Swift, if you are performing (for example) a network request inside a class, and in the completion of that request you reference a function that belongs to that class, you must pass
[weak self]…This is not true. Yes, it may be prudent or advisable to use the
[weak self]capture list, but it is not required. The only time you “must” use aweakreference toselfis when there is a persistent strong reference cycle.For well-written asynchronous patterns (where the called routine releases the closure as soon as it is done with it), there is no persistent strong reference cycle risk. The
[weak self]is not required.Nonetheless, weak capture lists are useful.
Using
[weak self]in these traditional escaping closure patterns still has utility. Specifically, in the absence of theweakreference toself, the closure will keep a strong reference toselfuntil the asynchronous process finishes.A common example is when you initiate a network request to show some information in a scene. If you dismiss the scene while some asynchronous network request is in progress, there is no point in keeping the view controller in memory, waiting for a network request that merely updates the associated views that are long gone.
Needless to say, the
weakreference toselfis really only part of the solution. If there’s no point in retainingselfto wait for the result of the asynchronous call, there is often no point in having the asynchronous call continue, either. E.g., we might marry aweakreference toselfwith adeinitthat cancels the pending asynchronous process.Weak capture lists are less useful in Swift concurrency.
Consider this permutation of your
function2:func function2() { Task { [weak self] in let result = await apiClient.performNetworkRequestAsync() self?.printSomething() } }This looks like it should not keep a strong reference to
selfwhileperformNetworkRequestAsyncis in progress. But the reference to a property,apiClient, will introduce a strong reference, without any warning or error message. E.g., below, I letAsyncClassfall out of scope at the red signpost, but despite the[weak self]capture list, it was not released until the asynchronous process finished:The
[weak self]capture list accomplishes very little in this case. Remember that in Swift concurrency there is a lot going on behind the scenes (e.g., code after the “suspension point” is a “continuation”, etc.). It is not the same as a simple GCD dispatch. See Swift concurrency: Behind the scenes.If, however, you make all property references
weak, too, then it will work as expected:func function2() { Task { [weak self] in let result = await self?.apiClient.performNetworkRequestAsync() self?.printSomething() } }Hopefully, future compiler versions will warn us of this hidden strong reference to
self.Make tasks cancelable.
Rather than worrying about whether you should use
weakreference toself, one could consider simply supporting cancelation:var task: Task<Void, Never>? func function2() { task = Task { let result = await apiClient.performNetworkRequestAsync() printSomething() task = nil } }And then,
@IBAction func didTapDismiss(_ sender: Any) { task?.cancel() dismiss(animated: true) }Now, obviously, that assumes that your task supports cancelation. Most of the Apple async API does. (But if you have written your own
withUnsafeContinuation-style implementation, then you will want to periodically checkTask.isCancelledor wrap your call in awithTaskCancellationHandleror other similar mechanism to add cancelation support. But this is beyond the scope of this question.)
Solution 2:[2]
if you are performing (for example) a network request inside a class, and in the completion of that request you reference a function that belongs to that class, you must pass [weak self] in, like this
This isn't quite true. When you create a closure in Swift, the variables that the closure references, or "closes over", are retained by default, to ensure that those objects are valid to use when the closure is called. This includes self, when self is referenced inside of the closure.
The typical retain cycle that you want to avoid requires two things:
- The closure retains
self, and selfretains the closure back
The retain cycle happens if self holds on to the closure strongly, and the closure holds on to self strongly — by default ARC rules with no further intervention, neither object can be released (because something has retained it), so the memory will never be freed.
There are two ways to break this cycle:
Explicitly break a link between the closure and
selfwhen you're done calling the closure, e.g. ifself.actionis a closure which referencesself, assignniltoself.actiononce it's called, e.g.self.action = { /* Strongly retaining `self`! */ self.doSomething() // Explicitly break up the cycle. self.action = nil }This isn't usually applicable because it makes
self.actionone-shot, and you also have a retain cycle until you callself.action(). Alternatively,Have either object not retain the other. Typically, this is done by deciding which object is the owner of the other in a parent-child relationship, and typically,
selfends up retaining the closure strongly, while the closure referencesselfweakly viaweak self, to avoid retaining it
These rules are true regardless of what self is, and what the closure does: whether network calls, animation callbacks, etc.
With your original code, you only actually have a retain cycle if apiClient is a member of self, and holds on to the closure for the duration of the network request:
func performRequest() {
apiClient.performRequest { [weak self] result in
self?.handleResult(result)
}
}
If the closure is actually dispatched elsewhere (e.g., apiClient does not retain the closure directly), then you don't actually need [weak self], because there was never a cycle to begin with!
The rules are exactly the same with Swift concurrency and Task:
- The closure you pass into a
Taskto initialize it with retains the objects it references by default (unless you use[weak ...]) Taskholds on to the closure for the duration of the task (i.e., while it's executing)- You will have a retain cycle if
selfholds on to theTaskfor the duration of the execution
In the case of function2(), the Task is spun up and dispatched asynchronously, but self does not hold on to the resulting Task object, which means that there's no need for [weak self]. If instead, function2() stored the created Task, then you would have a potential retain cycle which you'd need to break up:
class AsyncClass {
var runningTask: Task?
func function4() {
// We retain `runningTask` by default.
runningTask = Task {
// Oops, the closure retains `self`!
self.printSomething()
}
}
}
If you need to hold on to the task (e.g. so you can cancel it), you'll want to avoid having the task retain self back (Task { [weak self] ... }).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |

