https://kotlinlang.org logo
Title
l

Lokik Soni

06/18/2022, 5:28 PM
Hi all I am getting color from state different in two places in same screen. State class:
data class AddEditNoteState(
   val color: Int = Note.noteColors.random().toArgb(),
)
In ViewModel:
private val _addEditNoteSate = MutableStateFlow(AddEditNoteState())
val addEditNoteState = _addEditNoteSate
   .asStateFlow()
   .stateIn(viewModelScope, WhileViewSubscribed, AddEditNoteState())
In Compose:
val addEditNoteState by rememberFlowWithLifecycle(viewModel.addEditNoteState).collectAsState(AddEditNoteState())
val noteBackgroundColor = remember {
   Animatable(
      Color(if (noteColor != -1) noteColor else addEditNoteState.color)
   )
}
Now when I access addEditNoteState.color and noteBackgroundColor.value Both are different. Not able to find the error. Note (noteColor != -1) is not true means we are using addEditNoteState.color in Animatable*
z

Zach Klippenstein (he/him) [MOD]

06/22/2022, 8:03 PM
So you’re initializing the
noteBackgroundColor
to
addEditNoteState.color
, and then they’re different – does `addEditNoteState`’s value change after that initialization?
l

Lokik Soni

06/25/2022, 4:42 PM
There was a problem in using rememberFlowWithLifecycle with collectAsState() in compose. Only using collectAsState() will work perfectly.