https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
m

myrronth

10/15/2020, 1:17 PM
How do I declare a weak variable with the expect/actual pattern that also becomes a weak variable when used in Swift? I’ve tried
actual var listener: WeakReference<T>? = null
and updated my calls to
listener?.get()?.method()
. But once I use my shared code in Swift, the
listener
variable is not the expected
weak var listener: T
but a wrapped
KotlinWeakReference
. If I use this, it is the same as without – the value assigned to listener, a UIViewController, does not get deallocated once all the references in the concrete implementation are gone (the view controller gets dismissed and should not receive further messages from the listener)
a

AnaR

10/24/2020, 5:35 PM
I wrote one for my project. Common was the minimal i needed: expect class WeakRef<T:Any> (referred:T) { fun get(): T? }
Android Implemenation: actual typealias WeakRef<T> = WeakReference<T>
And ios impl: actual class WeakRef<T:Any> actual constructor(referred:T) { val delegate:WeakReference<Any> init { delegate = WeakReference(referred) } actual fun get(): T? { return delegate.get() as? T } }
I remember I had a similar memory leak as you described that went away after.
m

myrronth

10/26/2020, 6:10 AM
Thanks! In the meantime, I solved it using a proxy object in iOS (outside the lib) that holds a weak var to my controller. The proxy objects lifetime depends on the memory management of kotlin, but at least the memory-heavy ViewController gets released once the controller is no longer used.
3 Views