https://kotlinlang.org logo
#android
Title
# android
t

Travis Griggs

07/06/2020, 6:13 PM
Why does the following line not work:
Copy code
this.mainLayout.removeCallbacks(this::stopConnecting)
But if the following does:
Copy code
val stopConnectingRunnable = Runnable { this.stopConnecting() }
this.mainLayout.removeCallbacks(this.stopConnectingRunnable)
We thought (erroneously apparently and to much confusion/frustration) that the first would work.
e

ephemient

07/06/2020, 10:38 PM
why would you think that? it doesn't work like that in Java either
m

Mark Murphy

07/06/2020, 11:49 PM
removeCallbacks()
takes not just any
Runnable
, but the
Runnable
that you registered previously using
post()
or
postDelayed()
. So, you need to have a reference to the real
Runnable
that you used originally. If in your second code snippet you used
stopConnectingRunnable
for the original
postDelayed()
call (or whatever) and for the
removeCallbacks()
call, that is why it works. Conversely, if you let the compiler convert your function reference into a
Runnable
in both of those places, they would be different
Runnable
objects, and the
removeCallbacks()
one would not match the originally-registered one.
16 Views