I know this have been asked many times, but none of the solutions helped me.
I have a StateFlow<String?>
that is supposed to guard a token when it arrives from an API call.
it is implemented in the ViewModel as follows:
@HiltViewModel
class MainViewModel
@Inject constructor(
@Named("apiService")
private val apiService: IApiService,
@Named("mkApiService")
private val mkIMKApiService: IMKApiService,
private val dsManager: IDataStoreManager
) : ViewModel() {
private val _token = MutableStateFlow<String?>(null)
val token: StateFlow<String?>
get() = _token
fun setToken(newToken: String) { _token.value = newToken }
...
}
This is the composable i’m trying to update:
@RootNavGraph(start = true)
@Destination
@Composable
fun LoginScreen(
modifier: Modifier = Modifier,
navigator: NavController,
onBiometricLogin: () -> Unit = {}
) {
val viewModel = hiltViewModel<MainViewModel>()
val userPreferences by viewModel.userPreferences.collectAsState(
initial = UserPreferences()
)
val token by viewModel.token.collectAsState()
var loginType by remember { mutableStateOf<LoginType>(LoginType.NONE) }
Text(text = token ?: "Null")
AnimatedVisibility(visible = token != null) {
// Content that's supposed to appear
}
....
}
However, the AnimatedVisibility never shows its content, nor the Text() updates.
I need the Composable to update when token != null
I obviously already confirmed that its value is being correctly updated inside the ViewModel by logging the private val after a sucessful API call
Re-composition Works When the Flow Emit a new value and you are changing the value so it will not update
the solution is
suspend fun setToken(newToken: String) {
_token.emit(newToken)
}