Text in jetpack compose not showing text?

Viewed 307

This class simply emit character after 1-sec delay

class MainViewModel: ViewModel() {
    var bouncingName = flow<Char> {
        val text="hemant"
        for (letter in text){
            delay(1000L)
            emit(letter)
        }
    }
}

This main class displays string after concatenating string display on the app

class MainActivity : ComponentActivity() {
    @SuppressLint("CoroutineCreationDuringComposition")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            CompleteGuideKotlinFlowTheme {
                // A surface container using the 'background' color from the theme
                var letter by remember {
                    mutableStateOf(StringBuilder())
                }
                val viewModel = viewModel<MainViewModel>()
                //  var currentValue=viewModel.countDownValue.collectAsState(initial = 10)
                lifecycleScope.launch {
                    viewModel.bouncingName.collect {
                        letter.append(it)
                        Log.d("TAG", "Character in main $letter")
                    }
                }

                Box(modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center) {
                    Text(
                        text = letter.toString(),
                        fontSize = 30.sp
                    )
                }
            }
        }
    }
}

But nothing is showing on the app.
I don't understand why?

1 Answers

StringBuilder is mutable. When you append to it, Compose doesn't get notified and the recomposition doesn't happen. You should use immutable types with MutableState and update it using MutableState's setter:

var letter by remember { mutableStateOf("") }
...
letter = letter + it
Related