I have a flow continuously receiving from backend new values, which I transform to screen offsets for animation purposes and put in a map called markersMap
:
receivedFlow.value?.let { received ->
markersMap[received.stationId]?.offset = markersMap[received.stationId]?.nextOffset
markersMap[received.stationId]?.nextOffset = Offset(received.x, received.y)
}
Then I have a composable looping each second over all items in markersMap
, in order to create an animation from their previous offset to their next offset
@Composable
fun NativeMarkersAnimator() {
val offsetsMap = remember {
mutableStateMapOf<Long, Animatable<Offset,AnimationVector2D>>()
}
LaunchedEffect(Unit) {
while (true) {
markersMap.forEach { marker ->
val targetOffset = marker.value.futureOffset
targetOffset?.let { target ->
offsetsMap[marker.value.stationId] =
Animatable(marker.value.offset, Offset.VectorConverter)
offsetsMap[marker.value.stationId]?.animateTo(target, tween(900))
}
}
delay(1000)
}
}
//CANVAS
}
and obviously, also withinNativeMarkersAnimator
, the Canvas that will recompose for rendering animations:
@Composable
fun NativeMarkersAnimator() {
val offsetsMap = remember {
mutableStateMapOf<Long, Animatable<Offset,AnimationVector2D>>()
}
// LAUNCHED EFFECT in code snippet above
Canvas(modifier = Modifier.fillMaxSize()) {
offsetsMap.forEach { offset ->
val image = markersMap[offset.key]?.bitmap?.asImageBitmap()
image?.let {
drawImage(
image = image,
topLeft = offset.value.value
)
}
}
}
}
My issue: the values of markersMap
found in LaunchedEffect are not consistent with the values received from the flow: if I get from the flow e.g. Offset(400,300), I put it into markersMap
at the key x, I get an entry <x, Offset(400,300)>.
But during the Launched Effect loop I find a totally different value from the same entry, not <x,Offset(400,300)> but lets say <x, Offset(600,600)>, the value looks random or very old and it remains the same a lot, let’s say I update 20 times the entry from the flow, but from the LaunchedEffect it’s still the same (wrong) value. This means the offset anim will start from the same point a lot of times!
So the results is that animations kinda loop, starting from the same initial offset point and doing the same path again and again.
I think the issue is complex and that’s the reason chatgpt can’t help so much. Any hint would be of huge worth. Thanks in advance