benkuly
09/15/2021, 4:57 PMcomponentContext
? Should it contain a new CoroutineScope or should it expose suspending functions and the component should handle it (e. g. with rememberCoroutineScope
)?Arkadii Ivanov
09/15/2021, 5:16 PMfun CoroutineScope(context: CoroutineContext, lifecycle: Lifecycle): CoroutineScope {
val scope = CoroutineScope(context)
lifecycle.doOnDestroy(scope::cancel)
return scope
}
And then use it as follows:
class SomeComponent(componentContext: ComponentContext): ComponentContext by componentContext {
private val scope = CoroutineScope(Dispatchers.Main, lifecycle)
}
Francis Mariano
09/15/2021, 6:08 PMbenkuly
09/19/2021, 11:06 AMArkadii Ivanov
09/19/2021, 11:20 AM@Composable
function, then it will be bound to the composition's lifecycle. When push another screen to the stack, the scope will be cancelled. In most of the cases we want jobs bound to component lifecycles instead.
And the point about testing is yet another one. Testing normal functions is always simpler. You can pass "main" context via constructor, so in production it will be Dispatchers.main
, and in tests you can use e.g. Dispatchers.unconfined
.
class SomeComponent(
componentContext: ComponentContext,
mainContext: CoroutineContext = Dispatchers.main,
) { ... }
benkuly
09/19/2021, 11:36 AMscope.launch
. So in the test, when the function is called, it return immediatly and we have to find a way to wait until the code within the scope.launch
has finished. I don't know a nice way to do that.Arkadii Ivanov
09/19/2021, 11:40 AMlaunch
synchronously. If you target only Android, the you can use TestDispatcher
, which provides ability to manually control execution.