Home > database >  How to make an inline function remove itself when its being used as a listener in kotlin
How to make an inline function remove itself when its being used as a listener in kotlin

Time:09-24

I have hit a wall with this one and I can't find any question with a solution for this here in SO.

I am using a PagingAdapter method, from Google's Paging library, that receives an inline function as a listener:

    fun addLoadStateListener(listener: (CombinedLoadStates) -> Unit) {
        differ.addLoadStateListener(listener)
    }

And then to remove the listener they provide the following method

    fun removeLoadStateListener(listener: (CombinedLoadStates) -> Unit) {
        differ.removeLoadStateListener(listener)
    }

And I am using it like this

myPagingAdapter.addLoadStateListener { it: CombinedLoadStates -> 
    myPagingAdapter.removeLoadStateListener(this)
}

I know the above does not work, but it worked when the file was written in java since it had a correct reference to itself inside its own function. However, in Kotlin I cannot find a way to do this at all. I tried turning into an anonymous function, but it still won't pass the correct context

myPagingAdapter.addLoadStateListener { fun(it: CombinedLoadStates) -> 
    myPagingAdapter.removeLoadStateListener(this)
}

At this point I have no idea how I can remove an inline function that can't reference itself, and I cannot find any documentation with a solution for this anywhere.

How can I remove in kotlin an inline function by referencing itself?

CodePudding user response:

You can create a local function to reference itself:

fun myFun(CombinedLoadStates): Unit {
    myPagingAdapter.removeLoadStateListener(::myFun)
}

myPagingAdapter.addLoadStateListener(::myFun)

CodePudding user response:

If I understand correctly, you need a reference of inline function which was passed in addLoadStateListener so you can pass in removeLoadStateListener. You can try this

myPagingAdapter.addLoadStateListener(object :  (String) -> Unit {
        override fun invoke(p1: String) {
            myPagingAdapter.removeLoadStateListener(this)
        }

    })
  • Related