Reputation: 41
I'm student studying ios developer
I wonder how Driver doen't make circular reference?
below two codes show different result
// viewController deinit
publishRelay
.asDriver(onErrorJustReturn: "")
.drive(self.publishRelay2)
.disposed(by: disposeBag)
// viewContoller doen't deinit
publishRelay
.subscribe(onNext: { [self] _ in
self.publishRelay2.onNext("")
})
.disposed(by: disposeBag)
I watched drive code but there is node code to refer self as weak reference.
below is drive method, strong reference occur
please help me solve this problem thanks
Upvotes: 1
Views: 49
Reputation: 275015
You are correct that drive
does not create a weak reference from the subscription to self
(the view controller). In fact, it does not create any references to self
at all. That is why there is no retain cycle.
.drive(self.publishRelay2)
does not pass self
to drive
. It only passes publishRelay2
to drive
. self
here is merely qualifying publishRelay2
, to say "I mean the publishRelay2
property of self
, not some other property called publishRelay2
". If there are no name conflicts, this self
would be redundant.
The subscription would have a strong reference to publishRelay2
. This can be seen in the implementation of drive
, as the closure passed to subscribe
captures observers
. But this on its own does not create a retain cycle, since there are no strong references from publishRelay2
to self
.
In the .subscribe(onNext: { [self] _ in ... }
case on the other hand, you are passing a closure that strongly captures self
. The subscription will have a strong reference to the closure, and the closure has a strong reference to self
.
If the closure had only captured publishRelay2
instead, there will also be no retain cycles:
.subscribe(onNext: { [publishRelay2] _ in
publishRelay2.onNext("")
}
// or if there is a name conflict and "self." is not redundant:
.subscribe(onNext: { [relay = self.publishRelay2] _ in
relay.onNext("")
}
Upvotes: 2