Skip to content

Instantly share code, notes, and snippets.

@inamiy
Created December 2, 2022 11:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inamiy/e0e44f35e569ca1dd05eb8ef70f8656d to your computer and use it in GitHub Desktop.
Save inamiy/e0e44f35e569ca1dd05eb8ef70f8656d to your computer and use it in GitHub Desktop.
Avoid @_implicitSelfCapture pitfall by always adding `[weak self]` in `Task.init` closure
// Always use `[weak self]` explicitly here to prevent `self` from being retained until the end of Task scope.
//
// NOTE:
// Because of `Task.init` having `@_implicitSelfCapture` by (bad) API design,
// without `[weak self]` will cause implicit strong `self` reference, which may never get deallocated
// especially when using `for await`.
//
// See also: https://twitter.com/inamiy/status/1544252986339504128
Task { [weak self] in
for await x in sequence {
...
// With `[weak self]`, there is a chance of `self` getting deallocated in the mid of for-await loop.
}
// Without `[weak self]`, `self` is kept retained until the end of async scope.
// If `for await` is never-ending stream, `self` will never be deallocated!
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment