Yes, it can be done, but we need to make sure that we stop Coroutines from running after their `ViewHolder` is recycled. Otherwise, the previous `Coroutine` might replace the current content.
As for the `CoroutineScope`, as outlined in [this answer](https://stackoverflow.com/questions/67431845/coroutines-inside-recycler-adapter), a good option is to use ViewModelScope.
We can store the `Job` returned by the `Coroutine` in a `HashMap<ViewHolder, Job>`. Once there is a new `Coroutine` created, we cancel the `Job` associated to the same `ViewHolder`, if it is still active.
Define a `HashMap` in your `Adapter`:
```kotlin
private val jobs = HashMap<ViewHolder, Job>()
```
Then in your `onBindViewHolder`:
```
override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {
val job = CoroutineScope(Dispatchers.Default).launch {
// your logic...
}
// cancel the previous job (you can check if its still active too)
jobs[viewHolder]?.cancel()
jobs[viewHolder] = job
}
```
P.S. Using `position` as the hashmap key will not work, as the previous coroutine assigned to the `ViewHolder` is of a different position, and thus the previous `Job` will not be cancelled.
Yes, it can be done, but we need to make sure that we stop Coroutines from running after their `ViewHolder` is recycled. Otherwise, the previous `Coroutine` might replace the current content.
As for the `CoroutineScope`, as outlined in [this answer](https://stackoverflow.com/questions/67431845/coroutines-inside-recycler-adapter), a good option is to use ViewModelScope.
We can store the `Job` returned by the `Coroutine` in a `HashMap<ViewHolder, Job>`. Once there is a new `Coroutine` created, we cancel the `Job` associated to the same `ViewHolder`, if it is still active.
Define a `HashMap` in your `Adapter`:
```kotlin
private val jobs = HashMap<ViewHolder, Job>()
```
Then in your `onBindViewHolder`:
```
override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {
val job = CoroutineScope(Dispatchers.Default).launch {
// your logic...
}
// cancel the previous job (you can check if its still active too)
jobs[viewHolder]?.cancel()
jobs[viewHolder] = job
}
```
P.S. Using `position` as the hashmap key will not work, as the previous coroutine assigned to the `ViewHolder` is of a different position, and thus the previous `Job` will not be cancelled.