After having read this article about Memory Leaks, I am wondering whether using lambdas in Kotlin Android project is safe. It\'s true that lambda syntax makes me program wit
Here's a simple example of a leak, where the closure/block captures this:
class SomeClass {
fun doWork() {
doWorkAsync { onResult() } // leaks, this.onResult() captures `this`
}
fun onResult() { /* some work */ }
}
You'll need to use a WeakReference.
fun doWork() {
val weakThis = WeakReference(this)
doWorkAsync { weakThis?.get()?.onResult() } // no capture, no leak!
}
It'd be great if Kotlin copied the [weak self] idea from Swift.