Skip to content

Using Mutable Shared Flow

Devrath edited this page Jan 21, 2024 · 3 revisions

1_6gh2Ttj_yiu1SeYVETlvog

About the mutable shared flow

  • This flow is a type of Shared flow
  • It provides additional functions like

Code

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)
    }

}
Clone this wiki locally