0

I have two LaunchedEffect scopes like this :

 LaunchedEffect(key1 = mainViewModel.myvlue.value){ mainViewModel.updatemyvalue(1f) } LaunchedEffect(key1 = mainViewModel.myvlue.value){ mainViewModel.updatemyvalue(0f) } 

Both are implemented inside this method :

@Composable fun TabContent( pagerState: PagerState,count:Int,mainViewModel: MainViewModel) { HorizontalPager(state = pagerState, count = count) { index -> when (index) { 0 -> { LaunchedEffect(key1 = mainViewModel.myvlue.value){ mainViewModel.updatemyvalue(1f) } SecondScreen(mainViewModel) } 1 -> { LaunchedEffect(key1 = mainViewModel.myvalue.value) { mainViewModel.updatemyvalue(0f) } firstScreen(mainViewModel) } } } } 

The problem is that when one of these scopes launches, second one will be automatically called .

I know this is normal that when the key1 value changes scopes will be relaunched . but I just want them to be called separately when I navigate to their respective page inside HorizontalPager.

As you can see above, they will be called simultaneously when one of the executes.

what should I do ?

6
  • It is not clear why you should use a side effect in this way clicking a button. Commented Feb 8, 2023 at 22:51
  • That was wrong. I've edited the post. Commented Feb 8, 2023 at 23:05
  • Why not just remove the LaunchedEffects, are they needed for some reason? Commented Feb 8, 2023 at 23:42
  • Compose code needs to be side effect free. Because Composables can run at any time, in parallel or not at all. If I do not use this block, My code is not guaranteed to be executed at all. More info : developer.android.com/jetpack/compose/mental-model#parallel Commented Feb 9, 2023 at 0:03
  • Have you tried moving LaunchedEffects out of the HorizontalPager, then use a boolean to determine which to use. LaunchedEffect(yourBoolean){ ..., set the boolean to true or false in your HorizontalPager and it should trigger the LaunchedEffect when true or when false for the second Launched Effect Commented Feb 9, 2023 at 0:46

1 Answer 1

3

You should use the current index below in the way I posted in the attachment

Please test

// Page change callback LaunchedEffect(pagerState) { snapshotFlow { pagerState.currentPage }.collect { page -> when (page) { 0 -> viewModel.updatemyvalue() // First page 1 -> // Second page else -> // Other pages } } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.