Zoltan Demant
09/09/2021, 12:24 PMLazy<Foo>
in my MainActivity that takes 1000 ms to resolve; how can I .get()
it inside a @Composable
function such that it happens in the background (e.g. with Dispatchers.Default
)?Tiago Nunes
09/09/2021, 12:48 PMproduceState
. Or you could create a StateFlow
in the viewModel, launch a coroutine and update the value, and collect it as state in the @Composable
function.Zoltan Demant
09/09/2021, 12:58 PM@Composable
private fun rootController(
context: Context
): RootController? {
val controller by produceState<RootController?>(
initialValue = null,
producer = {
value = withContext(Default) {
PhoneComponent
.get(context)
.rootController()
}
}
)
return controller
}
Tiago Nunes
09/09/2021, 1:02 PMTiago Nunes
09/09/2021, 1:19 PMprivate fun getRootControllerFlow(context: Context) =
flow { emit(PhoneComponent.get(context)) }
.flowOn(Dispatchers.Default)
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(), null)
@Composable
fun Screen() {
val rootController by getRootControllerFlow(LocalContext.current).collectAsState()
}
Zoltan Demant
09/09/2021, 1:50 PMTiago Nunes
09/09/2021, 1:57 PMval context = LocalContext.current
val rootController by remember(context) { getRootControllerFlow(context) }.collectAsState()
Zoltan Demant
09/09/2021, 2:45 PMproduceState
?