-
Notifications
You must be signed in to change notification settings - Fork 22
Using Mutable Shared Flow
Devrath edited this page Jan 21, 2024
·
3 revisions
- This flow is a type of
Shared flow
- It provides additional functions like
- Provides the abilities to emit a value.
- Here also can tryEmit without suspension if possible.
- It can track the subscriptionCount
- It can resetReplayCache.
View
@Composable
fun MutableStateOfFlowDemo(navController: NavHostController){
val viewModel: MutableStateOfFlowDemoVm = hiltViewModel()
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
val coroutineScope = rememberCoroutineScope()
Spacer(modifier = Modifier.height(16.dp))
AppButton(text = "Start producing emissions", onClick = {
coroutineScope.launch {
repeat(100){
viewModel.produce(it)
}
}
})
Spacer(modifier = Modifier.height(10.dp))
LaunchedEffect(key1 = true){
coroutineScope.launch {
viewModel.data.collect{
println("Consumed -> $it")
}
}
}
}
}
VideModel
class MutableStateOfFlowDemoVm @Inject constructor(
@ApplicationContext private val context: Context,
) : ViewModel() {
private val _data = MutableSharedFlow<Int>(0)
val data = _data.asSharedFlow()
suspend fun produce(value : Int) {
println("Emitted value -> $value")
_data.emit(value)
}
}