Coroutine inside ViewHolder? [Kotlin]

Viewed 2704

I'm wondering if it's possible launch a Coroutine inside ViewHolder, I mean, Imagine that you press an item inside OnBindViewHolder and you need to call an API to get a response... I don't know if I could use Coroutines inside it!

Thank you so much

PS. Or Something like this

lblDeliveryMethod.setOnClickListener {
           // API CALL
            APICALLING()
            suspend {
                delay(1000)
                withContext(Dispatchers.Main) {
                    if (APIRESPONSES) {
                        // DO SOMETHING
                   
                    }
                }
            }
        }
2 Answers

Do not do this, this is plain wrong. Perform background work inside the components that are designed for it, like the ViewModel, which has a Lifecycle that survives configuration changes and has a CoroutineScope that is tied to the ViewModel's Lifecycle.

Your ViewHolder should provide a way for the Fragment/Activity that hosts the RecyclerView to register an onClickListener, and call a method on the ViewModel when it is clicked.

You can either take a lambda as a constructor parameter on your list item, or have a setOnClickListener() method on the list item, and a property to store it.

Related