@@ -2,6 +2,7 @@ package com.squareup.workflow1.ui
22
33import android.content.Context
44import android.os.Build.VERSION
5+ import android.os.Looper
56import android.os.Parcel
67import android.os.Parcelable
78import android.os.Parcelable.Creator
@@ -20,6 +21,7 @@ import kotlinx.coroutines.CoroutineDispatcher
2021import kotlinx.coroutines.Job
2122import kotlinx.coroutines.flow.Flow
2223import kotlinx.coroutines.launch
24+ import kotlinx.coroutines.withContext
2325import kotlin.coroutines.CoroutineContext
2426import kotlin.coroutines.EmptyCoroutineContext
2527
@@ -89,8 +91,8 @@ public class WorkflowLayout(
8991 * @param [repeatOnLifecycle] the lifecycle state in which renderings should be actively
9092 * updated. Defaults to STARTED, which is appropriate for Activity and Fragment.
9193 * @param [collectionContext] additional [CoroutineContext] we want for the coroutine that is
92- * launched to collect the renderings. This should not override the [CoroutineDispatcher][kotlinx.coroutines.CoroutineDispatcher]
93- * but may include some other instrumentation elements.
94+ * launched to collect the renderings, can include a different dispatcher - but it should be
95+ * a main thread dispatcher!
9496 *
9597 * @return the [Job] started to collect [renderings], to give callers the option to
9698 * [cancel][Job.cancel] collection -- e.g., before calling [take] again with a new
@@ -104,16 +106,15 @@ public class WorkflowLayout(
104106 repeatOnLifecycle : State = STARTED ,
105107 collectionContext : CoroutineContext = EmptyCoroutineContext
106108 ): Job {
107- // We remove the dispatcher as we want to use what is provided by the lifecycle.coroutineScope.
108- val contextWithoutDispatcher = collectionContext.minusKey(CoroutineDispatcher .Key )
109- val lifecycleDispatcher = lifecycle.coroutineScope.coroutineContext[CoroutineDispatcher .Key ]
110109 // Just like https://medium.com/androiddevelopers/a-safer-way-to-collect-flows-from-android-uis-23080b1f8bda
111- return lifecycle.coroutineScope.launch(contextWithoutDispatcher) {
110+ return lifecycle.coroutineScope.launch {
112111 lifecycle.repeatOnLifecycle(repeatOnLifecycle) {
113- require(coroutineContext[CoroutineDispatcher .Key ] == lifecycleDispatcher) {
114- " Collection dispatch should happen on the lifecycle's dispatcher."
112+ withContext(collectionContext) {
113+ require(Looper .myLooper() == Looper .getMainLooper()) {
114+ " Collection dispatch should happen on the main thread!"
115+ }
116+ renderings.collect { show(it) }
115117 }
116- renderings.collect { show(it) }
117118 }
118119 }
119120 }
0 commit comments