Felipe Passos
05/31/2021, 11:36 AMSe7eN
05/31/2021, 11:41 AMsuspend fun updateState(api: Api, onRecieve: (String) -> Unit) {
val notify = Channel<String>()
api.stream(notify)
while(true) {
onRecieve(notify.receive())
}
}
@SuppressLint("CoroutineCreationDuringComposition")
@Composable
fun SomeComposable(api: Api, locationViewModel: LocationViewModel = viewModel()) {
var state by remember { mutableStateOf("") }
val composableScope = rememberCoroutineScope()
composableScope.launch {
updateState(api, onRecieve = { state = it })
}
}
Felipe Passos
05/31/2021, 11:45 AMSe7eN
05/31/2021, 11:46 AMLaunchedEffect
Felipe Passos
05/31/2021, 11:47 AMSe7eN
05/31/2021, 11:47 AMFelipe Passos
05/31/2021, 11:49 AMFelipe Passos
05/31/2021, 11:50 AMSe7eN
05/31/2021, 11:50 AMSe7eN
05/31/2021, 11:52 AMupdateState
be in your view model?Felipe Passos
05/31/2021, 11:52 AMSe7eN
05/31/2021, 11:53 AMFelipe Passos
05/31/2021, 11:54 AMFelipe Passos
05/31/2021, 11:55 AMSe7eN
05/31/2021, 11:56 AMSe7eN
05/31/2021, 11:58 AMFelipe Passos
05/31/2021, 12:05 PMSe7eN
05/31/2021, 12:15 PMDominaezzz
05/31/2021, 12:16 PMfun updateState(api: Api): Flow<String>
that returns a channelFlow { .... }
. Then you can use collectAsState()
.Felipe Passos
05/31/2021, 12:18 PMDominaezzz
05/31/2021, 12:25 PMfun updateState(api: Api): Flow<String> {
return channelFlow<String> {
api.stream(this)
awaitClose { /* do closing things if needed */ }
}
}
Dominaezzz
05/31/2021, 12:26 PM@SuppressLint("CoroutineCreationDuringComposition")
@Composable
fun SomeComposable(api: Api, locationViewModel: LocationViewModel = viewModel()) {
val state by remember(api) { updateState(api) }.collectAsState("")
// do stuff with state
}
Felipe Passos
05/31/2021, 12:29 PMDominaezzz
05/31/2021, 12:30 PMFelipe Passos
05/31/2021, 12:55 PM