Kotlin : safe lambdas (no memory leak)?

前端 未结 3 2090
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-02 12:25

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

3条回答
  •  一个人的身影
    2020-12-02 12:53

    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.

提交回复
热议问题