I'm a bit kotlin newbie and I'm trying to remove the callback instance inside the callback itself.
What I'm trying to achieve it's something similar to the following code.
private val myCallback = SomeInterfaceType {
if(it.something) {
someObject.removeListener(this@SomeInterfaceType)
}
}
Of course it doesn't compile or else I wouldn't be asking here. So I ask, how to remove the callback from inside the instance of the interface?
edit: the error is "inferred type is X but Y was expected.
edit 2: I just realized I've asked the wrong question, it's similar to it but not exactly a Interface.
The object I'm using have the following constructor/interface
public open class Watcher<T> public constructor(call: (T) -> kotlin.Unit)
so in reality I'm trying to reference the Watcher from inside the call: (T) -> kotlin.Unit
to remove the listener.
Is that possible?
To remove all the callbacks. you need the reference for all the runnables which can be stored in an ArrayList. private ArrayList<Runnable> runnableQueue=new ArrayList<Runnable>(); Then every time u want to post a runnable, store it in the array, then post the array item using handler.
Android callbacks allow your method to fetch results from another method synchronously. Callbacks act as messengers; they are the center of communication in a program, and get passed into functions as arguments. They help in completing the task of a function by providing results, either negative or positive.
To remove a specific element from a Mutable List in Kotlin, call remove() function on this list object and pass the element, that we would like to remove, as argument.
You need to use a full object expression syntax to refer to be able to refer to the instance itself:
private val myCallback = object: SomeInterfaceType() {
override fun onSomeEvent() {
if (it.something) {
someObject.removeListener(this)
}
}
}
There's also a workaround: wrap the reference to myCallback
into a lambda passed to a function that calls it (e.g. run { ... }
):
private val myCallback: SomeInterfaceType = SomeInterfaceType {
if (it.something) {
someObject.removeListener(run { myCallback })
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With