Coroutines inside Recycler Adapter

Viewed 3200

for purposes of Room db. I want to run some coroutines inside Recycler View.

Necessary suspend functions are handled as a class parameters:

class RecyclerAdapter  (private val  exist : suspend (lastName : String) -> Boolean) 

And then, when needed I'm using following construction:

GlobalScope.launch(Dispatchers.IO) {
   if (exist(dataSet[position].lastName))
       [...]

I'm not sure if using the Global Scope is the best practice. I considered using lifecycleScope but in Adapter lifecycleOwner is not available, handling it as a parameter is not a good practice.

What would you guys suggest?

2 Answers

I think it goes against the single responsibility pattern, as the purpose of an adapter is mainly to take care of how the data is laid out.

I would move this information to the list of items, and do the call from the viewmodel, with:

viewModelScope.launch{}

than update a LiveData/StateFlow, observe it from the view, and submit the list to the adapter accordingly

I suggest to use:

CoroutineScope(Dispatchers.IO).launch {}
Related