When I post an lambda in Android, kotlin compiler automatically convert lambda to runnable by create a new Runnable object to wrap that lambda.
Then when I want to remove this callback, kotlin will create another new Runnable object to wrap my lambda.
Hence the removement won’t success.
val task = { }
// kotlin automatically convert task to Runnable { task() }
MainLooper.post(task)
// cannot remove this callback because
// Runnable { task() } is not the same one
MainLooper.removeCallbacks(task)
I know the correct way to write this. But why kotlin compiler make this dangerous conversion?
val task = Runnable { } // SAM conversion
MainLooper.post(task)
MainLooper.removeCallbacks(task) // successfully removed