I want to add support for coroutines inside my cus...
# coroutines
r
I want to add support for coroutines inside my custom
ListAdapter
. Is
onAttachedToRecyclerView/onDetachedFromRecyclerView
valid place to manage the scope?
Copy code
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
I'd recommend to use this solution by Yigit Boyar (from the AndroidX team): https://github.com/yigit/suspend-bind
r
But I want to do stuff inside the adapter, not the ViewHolder
l
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
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
You can inject a scope or job into the adapter, and create custom scope / jobs that are children of it.
👍 3