Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove "this" callback in kotlin

Tags:

android

kotlin

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?

like image 287
Budius Avatar asked Feb 12 '18 11:02

Budius


People also ask

How do I remove callback?

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.

What is callback in Kotlin?

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.

How do I remove a code from Kotlin?

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.


2 Answers

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)
        }
    }
}
like image 117
zsmb13 Avatar answered Nov 01 '22 04:11

zsmb13


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 })
   }
}
like image 40
hotkey Avatar answered Nov 01 '22 04:11

hotkey