'[weak self]' in RXSwift closures
If the closure is not owned by the class you do not have to use [weak self]
.
In the case of in-line closures the closure is not owned by the class but by the scope it is in and will be released when the scope is left.
If the closure is passed in it may or may not be owned by the class (a property for example) and it is prudent to use [weak self]
incase it is owned by the class.
Yes, you should create a weak capture of self
if you access self
within the closure and it is possible that self
could become nil
before the closure is called.
If a closure captures self
and then self
becomes nil
, when the closure is called and attempts to access that self
, you’ll get an exception.
Credit to scotteg, he has an example project on GitHub: https://github.com/scotteg/TestRxSwiftClosures
See the DetailViewController
in the example.
You can uncomment the other two examples, one at a time, to see the results. The first one doesn’t define a capture list at all, and the second one defines an unowned
capture. Run the app and enter some text and tap Done within 5 seconds (there’s a 5-second delay in each closure). The first two examples will result in exceptions being thrown.
The basic rule is this: If the capture (e.g., self
) can be set to nil
, such as if the instance it references gets deallocated, define the capture as weak
. Otherwise, if a closure and a capture within that closure will always refer to each other and be deallocated at the same time, define the capture as unowned
.