07-19-2023, 12:09 AM
I don't quite understand how to properly store subscribers inside a class so that they persist but don't prevent the object from being deinitialized. Here's an example where the object won't deinit:
```swift
import UIKit
import Combine
class Test {
public var name: String = ""
private var disposeBag: Set<AnyCancellable> = Set()
deinit {
print("deinit")
}
init(publisher: CurrentValueSubject<String, Never>) {
publisher.assign(to: \.name, on: self).store(in: &disposeBag)
}
}
let publisher = CurrentValueSubject<String, Never>("Test")
var test: Test? = Test(publisher: publisher)
test = nil
```
When I replace the `assign` with a `sink` (in which I properly declare `[weak self]`) it actually does deinit properly (probably because the `assign` accesses `self` in a way that causes problems).
How can I prevent strong reference cycles when using `.assign` for instance?
Thanks
```swift
import UIKit
import Combine
class Test {
public var name: String = ""
private var disposeBag: Set<AnyCancellable> = Set()
deinit {
print("deinit")
}
init(publisher: CurrentValueSubject<String, Never>) {
publisher.assign(to: \.name, on: self).store(in: &disposeBag)
}
}
let publisher = CurrentValueSubject<String, Never>("Test")
var test: Test? = Test(publisher: publisher)
test = nil
```
When I replace the `assign` with a `sink` (in which I properly declare `[weak self]`) it actually does deinit properly (probably because the `assign` accesses `self` in a way that causes problems).
How can I prevent strong reference cycles when using `.assign` for instance?
Thanks