https://kotlinlang.org logo
Title
r

Rafal

11/02/2021, 7:47 AM
I want to add support for coroutines inside my custom
ListAdapter
. Is
onAttachedToRecyclerView/onDetachedFromRecyclerView
valid place to manage the scope?
class CoroutineAdapter: ListAdapter<AdapterItem, AdapterViewHolder>() {

    private val coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)

    override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
        super.onAttachedToRecyclerView(recyclerView)
        coroutineScope.launch {
            // stuff made here
        }
    }

    override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
        super.onDetachedFromRecyclerView(recyclerView)
        coroutineScope.coroutineContext.cancelChildren()
    }
}
l

louiscad

11/02/2021, 9:18 AM
I'd recommend to use this solution by Yigit Boyar (from the AndroidX team): https://github.com/yigit/suspend-bind
r

Rafal

11/02/2021, 9:30 AM
But I want to do stuff inside the adapter, not the ViewHolder
l

louiscad

11/02/2021, 9:31 AM
Why?
I think that in some cases the
onDetachedFromRecyclerView
can not be called. It'd be best to scope the coroutines to what contains the adapter so that you definitely know then the scope is cancelled.
r

Rafal

11/02/2021, 9:35 AM
I am observing for the
recyclerView.scrollEvents(): Flow
inside the adapter, up until now we used RxBindings the same way, where we were disposing a
Disposable
in the
onDetachedFromRecyclerView
l

louiscad

11/02/2021, 9:37 AM
You can inject a scope or job into the adapter, and create custom scope / jobs that are children of it.
👍 3