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

Marc Knaup

08/23/2020, 3:53 PM
Is there an idiomatic way to memoize values that works multiplatform (and esp. across threads in Native)? E.g.
private val hash: Int by lazy { … }
but
lazy
doesn’t work across threads in Native afaik.
a

Arkadii Ivanov

08/23/2020, 4:19 PM
I guess there is no such a way in K/N currently. Mutex requires explicit destroy. I would go with something based on atomics.
s

saket

08/23/2020, 4:56 PM
a

Arkadii Ivanov

08/23/2020, 5:00 PM
Yep, but I would guess it can call the lambda multiple times under heavy concurrent access. Just like in normal atomics.
m

Marc Knaup

08/23/2020, 5:02 PM
Thanks, that sounds good! So I basically use
lazy
on JVM/JS and
atomicLazy
on native 🙂 The part “may potentially leak memory” sounds a bit worrying. But I don’t have cyclical references here so it’s probably OK. My operations are idempotent, so it’s okay if the lambda is called multiple times.
a

Arkadii Ivanov

08/23/2020, 5:06 PM
Then this is your way!
3 Views