gpaligot
01/06/2021, 8:16 AMfun myFunc(input: Input) = flow {
myDao.get().collect {
it.forEach {
emit(it.data)
delay(it.delayTime)
}
}
}
In my composable, I have something like this:
@Composable
fun MyComposable(input: Input) {
val myViewModel: MyViewModel = viewModel()
val data = myViewModel.myFunc(input).collectAsState()
AnotherComposable(data = data.value)
}
The issue is: When I emit new data from my flow, compose collect the data and recompose itself because the state has been updated but due to this recomposition, it recall myFunc
function, cancel the previous execution of the flow, collect data from database, emit values and loop a long time like this.
How can I change my code to avoid this loop? There is any good practice for my usecase?
Thanks in advance!gpaligot
01/06/2021, 8:51 AMmyFunc
and in my composable:
@Composable
fun MyComposable(input: Input) {
val myViewModel: MyViewModel = viewModel()
val inputState = remember { mutableStateOf(input.id) }
onActive {
myViewModel.myFunc(input)
}
onCommit {
if (inputState.value != input.id) {
myViewModel.myFunc(input)
inputState.value = input.id
}
}
val data = myViewModel.myStateFlow.collectAsState()
AnotherComposable(data = data.value)
}
Kshitij Patil
01/06/2021, 9:07 AMproduceState
will make sure that myFunc()
will be executed only once.
2) using kotlin's by
to get the value out of flow would also make some difference (atleast I use it this way)
3) If you know some subject
that causes the values being emitted via flow, you can use LaunchedEffect
to call myFunc
every time that subject changes
Also, I believe there should be no infinite loop by looking at the give code block as you're not using data.value
in MyComposable
anywhere and any changes in data.value
should only recompose the AnotherComposable
.gpaligot
01/06/2021, 11:00 AMdata.value
should only recompose the AnotherComposable