Created
December 2, 2022 11:03
-
-
Save inamiy/e0e44f35e569ca1dd05eb8ef70f8656d to your computer and use it in GitHub Desktop.
Avoid @_implicitSelfCapture pitfall by always adding `[weak self]` in `Task.init` closure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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