Reputation: 1056
I am trying to pass message from viewModel into my Screen Activity using collect in Android Jetpack compose, where I am trying to show snackbar but for some reason it is not changing background color and action button color (nor going in if condition) on snackbar and also it is not comparing to my string which I am passing and going in else condition always. Please advice how to handle this scenerio from Activity Screen
// From ViewModel
private val _showMessage = MutableSharedFlow<String>()
val showMessage get() = _showMessage.asSharedFlow()
_showMessage.emit("My custom message")
// From ViewController Activity
val scaffoldState: ScaffoldState = rememberScaffoldState()
SnackbarHost(scaffoldState.snackbarHostState) { data ->
// custom snackbar with the custom colors
Snackbar(
actionColor = Color.Blue,
backgroundColor = Color.Gray,
)
}
LaunchedEffect(scaffoldState.snackbarHostState) {
viewModel.showMessage.collect {
if (viewModel.showMessage.equals(“My custom message”)) {
scaffoldState.snackbarHostState.showSnackbar(it, "OK", SnackbarDuration.Indefinite)
} else {
println("view message ${viewModel.showMessage.equals("My custom message”)}”). /// Coming as false always
scaffoldState.snackbarHostState.showSnackbar(it)
}
}
}
Upvotes: 1
Views: 754
Reputation: 520
Add containerColor
to your snackbar to change background color of snackbar
Example:
val snackbarHostState = remember { SnackbarHostState() }
SnackbarHost(snackbarHostState) { data ->
Snackbar(
snackbarData = data,
containerColor = Color.Red // For changing snackbar background color
)
}
Upvotes: 3
Reputation: 67209
It's because viewModel.showMessage
is a SharedFlow<String>
not a String
.
You are collecting String you can do operations with it naming parameter or using as it
.
LaunchedEffect(scaffoldState.snackbarHostState) {
viewModel.showMessage.collect { message: String ->
if (message == "My custom message") {
}
}
Upvotes: 1