kotlinkotlin-coroutinesandroid-viewholder

Coroutine inside ViewHolder? [Kotlin]


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
                   
                    }
                }
            }
        }

Solution

  • I could fix it using this plugin... it works like a charm

    https://github.com/satoshun/CoroutineAutoDispose

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
      holder.itemView.autoDisposeScope.launch {
        ...
      }
    }