ursus
10/18/2020, 2:17 AMclass MainActivity : AppCompatActivity() {
private val scope = MainScope()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.d("Default", "a")
scope.launch {
Log.d("Default", "b")
flowOf(1)
.collect { Log.d("Default", "coll=$it t=${Thread.currentThread().name}") }
}
Log.d("Default", "c")
}
}
prints:
2020-10-18 04:14:26.808 21786-21786/sk.foo.flowplayground D/Default: a
2020-10-18 04:14:26.808 21786-21786/sk.foo.flowplayground D/Default: c
2020-10-18 04:14:26.848 21786-21786/sk.foo.flowplayground D/Default: b
2020-10-18 04:14:26.851 21786-21786/sk.foo.flowplayground D/Default: coll=1 t=main
I want:
2020-10-18 04:14:26.808 21786-21786/sk.foo.flowplayground D/Default: a
2020-10-18 04:14:26.808 21786-21786/sk.foo.flowplayground D/Default: b
2020-10-18 04:14:26.848 21786-21786/sk.foo.flowplayground D/Default: coll=1 t=main
2020-10-18 04:14:26.851 21786-21786/sk.foo.flowplayground D/Default: c
Ian Lake
10/18/2020, 2:45 AMMainScope()
? I think if you use lifecycleScope
you'll get the behavior you want since it uses Dispatchers.Main.immediate
by defaultursus
10/18/2020, 2:46 AMpackage kotlinx.coroutines
public fun MainScope(): CoroutineScope = ContextScope(SupervisorJob() + Dispatchers.Main)
ill try the immediate thanksIan Lake
10/18/2020, 3:18 AMlifecycleScope
also automatically handles cancellation when the activity is destroyed, so you always consider using that over creating your own scope. See the docs for more details: https://developer.android.com/topic/libraries/architecture/coroutines#lifecyclescopeursus
10/18/2020, 3:20 AMIan Lake
10/18/2020, 3:26 AMursus
10/18/2020, 3:28 AMZach Klippenstein (he/him) [MOD]
10/18/2020, 3:38 PMursus
10/18/2020, 4:12 PMZach Klippenstein (he/him) [MOD]
10/18/2020, 5:16 PMGlobalScope
is another one.ursus
10/18/2020, 6:48 PM