Use withContext to wait for an async operation

(cherry picked from commit 2787624027)
This commit is contained in:
Geoffrey Métais
2018-02-27 14:12:43 +01:00
parent 43b011eb6f
commit 7dedf17a6b

View File

@@ -9,6 +9,7 @@ import kotlinx.coroutines.experimental.channels.Channel
import kotlinx.coroutines.experimental.channels.actor
import kotlinx.coroutines.experimental.launch
import kotlinx.coroutines.experimental.newSingleThreadContext
import kotlinx.coroutines.experimental.withContext
import java.util.*
abstract class DiffUtilAdapter<D, VH : RecyclerView.ViewHolder> : RecyclerView.Adapter<VH>() {
@@ -32,11 +33,11 @@ abstract class DiffUtilAdapter<D, VH : RecyclerView.ViewHolder> : RecyclerView.A
private suspend fun internalUpdate(list: List<D>) {
val finalList = prepareList(list)
val result = DiffUtil.calculateDiff(diffCallback.apply { update(dataset, finalList) }, detectMoves())
launch(UI) {
withContext(UI) {
dataset = finalList
result.dispatchUpdatesTo(this@DiffUtilAdapter)
onUpdateFinished()
}.join()
}
}
protected open fun prepareList(list: List<D>) : List<D> = ArrayList(list)