While I understand or think I understand, what side-effects are in jet-pack compose.
It's any work done in composable which escapes the scope of the composable function
I understand doing stuff like I/O operations or mutating a variable outside of function scope, giving reference and not clearing it (memory leak), or mutating a local variable that is not composable state - these all are side-effects, as they can lead to unexpected behavior and leaks because of recomposition, which is not deterministic and can run many times. And to take care of side-effects, we have effect-handlers.
Considering everything above, I need a bit of clarity in a few scenarios
- Side-effect - in case of mutating object, does it holds true for any object other than compose object? As in compose states (mutableStateOf etc..) doesn't lead to side-effects? Why?
- Why callbacks/state/event hoisting to your activity/fragment/viewmodel,does not lead to side-effect?
For example
@Composable
fun MyComposable(
viewModel:MyViewModel,
launchSomeActivity:()->Unit
){
var state by remember { mutableStateOf("") }
state = "some string" // not a side-effect?
viewModel.someStringObject = "a" // it's a side-effect?
launchSomeActivity() // it's a side-effect?
when(val screenState = viewModel.screenState.collectAsState().value){
is ScreenState.Success -> launchSomeActivity() // not a side-effect. why?
is ScreenState.Error -> state="some String" // not a side-effect. why?
}
}
I also recall reading somewhere, trigger side-effects from callbacks, such as onClick as that always executes on UI thread, or say calling some lambda from ViewModel.
Would like to understand the above scenario as well, as in how it prevents side-effects, calling a lambda or a callback?