Problem:
- I have used
collectAsStateWithLifecycle
to collect the flow - Now once I initiate the flow and minimize the app still the flow is active
- According to
collectAsStateWithLifecycle
flow emission should get paused when app is minimized
ViewModel
@HiltViewModelclass CollectAsStateWithLifeCycleVm @Inject constructor( @ApplicationContext private val context: Context,) : ViewModel() { companion object { const val INITIAL_VALUE = 0 } private var currentTime = INITIAL_VALUE private val _data = MutableStateFlow(0) val data = _data.asStateFlow() init { initiate() } private fun initiate() { viewModelScope.launch { while(true){ delay(1000L) println("Flow is active current time ---> $currentTime") _data.emit(currentTime++) } } } val newTimer = flow { while(true){ delay(1000L) println("Flow is active current time ---> $currentTime") emit(currentTime++) } }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000L),0)}
Composable
@Composablefun CollectAsStateWithLifeCycleDemo(navController: NavHostController){ val viewModel: CollectAsStateWithLifeCycleVm = hiltViewModel() //val time = viewModel.data.collectAsStateWithLifecycle() //val time = viewModel.newTimer.collectAsStateWithLifecycle() val time: Int by viewModel.data.collectAsStateWithLifecycle() Column( modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Spacer(modifier = Modifier.height(16.dp)) Text( text = time.toString(), fontSize = 30.sp ) }}