Hey guys, I want to run `debounce` on a flow from within a Composable. I get this warning Flow opera...
s
Hey guys, I want to run
debounce
on a flow from within a Composable. I get this warning Flow operator functions should not be invoked within composition . I am not using Viewmodels so can’t run the flow operator in the VM. Ideally I’d just want to call
debounce
on the
fullNameFlow
and trigger some changes in the composable. What’s the best way to go forward?
Copy code
//This is inside a Composable
val fullNameFlow = MutableStateFlow("")
fullNameFlow.debounce(3000).mapLatest {
    Log.i(TAG,it)
    //Change Composable State
}

FormTextField(
    onValueChange = {
        fullNameFlow.value = it
    }
)
p
Reckon you should probably pass a function to your composable that your FormTextField can call within onValueChange, and move your StateFlow into your Fragment or Presenter layer.
Copy code
@Composable
fun Form(onUpdate: (String) -> Unit){
  FormTextField(){ latest ->
     onUpdate(latest)
   }
}
z
You always need to remember state that you create inside a composable, otherwise it will be recreated on every recomposition.
So eg
Copy code
val fullNameFlow = remember { MutableStateFlow(“”) }
LaunchedEffect(fullNameFlow) {
  // Don't need to remember here because the launched effect lives across recompositions.
  fullNameFlow
    .debounce(3000)
    .mapLatest { … }
    .collect { … }
}
s
Thanks @Zach Klippenstein (he/him) [MOD] !!!
This worked!
1136 Views