TheRock
TheRock

Reputation: 97

How to pass data from fragment to recycler view using interface

I know that I can pass data from RecyclerView to fragment easily, but I want to do other way around. I want to trigger an interface from fragment and have that interface implemented in ViewHolder for RecyclerView. This is my interface and ViewHolder.

interface ExampleListener{
    fun onListen()
}

ViewHolder:

inner class ViewHolder(val binding: ItemBinding) : RecyclerView.ViewHolder(binding.root), ExampleListener {

    ...

    override fun onListen() {
        // Do something
    }

    ...

 }

I don't know how to trigger this interface from fragment. I know that if I was trying to pass data to activity I would trigger interface like this:

override fun onAttach(context: Context) {
    super.onAttach(context)

    if (context is ExampleListener) {
        exampleListener = context
    } else {
        throw RuntimeException(requireContext().toString() + "must implement ExampleListener")
    }
}

Upvotes: 0

Views: 133

Answers (1)

mightyWOZ
mightyWOZ

Reputation: 8335

One way to do it to update your interface so that the function accepts a callback

interface ExampleListener{
    fun startDownloadAndListen(onComplete: () -> Unit)
}

Now in adapter when you start download on button click, simply pass this callback, which will be invoked when download completes

button.setOnClickListener {
    button.visibility = View.GONE
    // Show progress bar
    listener.startDownloadAndListen { 
        // hide progress bar etc.
        button.visibility = View.VISIBLE
     }
 }

finally implement ExampleListener in your Activity as

override fun startDownloadAndListen(onComplete: () -> Unit) {
    lifecycleScope.launch {
        val result = viewModel.startDownload()   // Start and wait 

        // Once result is available then call the onComplete
        withContext(Dispatchers.Main) { onComplete() }
    }
}

Upvotes: 1

Related Questions