Hi guys! Is there something like a `WeakReference`...
# multiplatform
a
Hi guys! Is there something like a
WeakReference
in Kotlin MPP? I have a custom
EventBus
implementation which returns
Subscription
objects whenever the user subscribes to an event. My problem is that it is easy to forget to call
Subscription.unsubscribe
and there can be memory leaks when the subscriber drops the reference to the
Subscription
but the
EventBus
retains it forever. Is there a best practice for this scenario in the context of MPP?
s
I’m not sure there is a
WeakReference
available in js, so I don’t think there is one. In JS, for the ES6, there is a
WeakMap
I think.
a
is there an alternative solution which I can use?
s
I mean, what platforms do you need it available for? You could make your own using expect / actual assuming you only wanted to support kotlin/native and kotlin/jvm
if you wanted to support js, you’d have to start doing some weird stuff to get access to weak references directly I think. I’m not an expert, but this is something I’ve tried to do / looked into previously
a
i target all platforms sadly 😞
except for native
s
so jvm has a weak map, and assuming you are targeting recent browsers, (or you can use a polyfill) you can use js weak map. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap
You could create a common wrapper around both of them I think
If you wanted to support ie11 or something like that, you’d have to use a polyfill
If you only wanted to support only certain JS platforms, like nodejs or something like that, you could gain access to the underlying native weak reference api. It’d get hairy pretty quickly if you wanted to support most browsers though, in which case, I’d definitely go for the WeakMap approach
a
I don't really care about old browsers
😄
thanks for the help
👍
c
This thread is a bit old, but just in case… There is now 🙂 https://opensavvy.gitlab.io/groundwork/pedestal/api-docs/weak/index.html