mikolaj-jalocha
mikolaj-jalocha

Reputation: 728

Coroutines inside Recycler Adapter

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?

Upvotes: 5

Views: 9220

Answers (4)

faribakhandani
faribakhandani

Reputation: 49

I suggest that CoroutineScope(Dispatchers.IO).launch {} with withContext(Dispatchers.Main){} that helps to update the Recycler View

Upvotes: 0

Ji Sungbin
Ji Sungbin

Reputation: 1321

You can get LifecycleCoroutineScope in onBindViewHolder.

override fun onBindViewHolder(holder: EventViewHolder, position: Int) {
    val coroutineScope =
        holder.itemView.findViewTreeLifecycleOwner()?.lifecycleScope ?: CoroutineScope(Dispatchers.IO)
}

But as Róbert Nagy said, I don't think it's a good idea to deal directly with business logic inside RecyclerView.

Upvotes: 0

Róbert Nagy
Róbert Nagy

Reputation: 7680

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

Upvotes: 10

Andrey Kijonok
Andrey Kijonok

Reputation: 416

I suggest to use:

CoroutineScope(Dispatchers.IO).launch {}

Upvotes: 4

Related Questions