Skip to content

Instantly share code, notes, and snippets.

@dilrajsingh1997
Last active June 28, 2022 18:20
Show Gist options
  • Save dilrajsingh1997/cbbf9c5f6c4bb8a42a6ab2a123836a29 to your computer and use it in GitHub Desktop.
Save dilrajsingh1997/cbbf9c5f6c4bb8a42a6ab2a123836a29 to your computer and use it in GitHub Desktop.
val itemsToAnimate = remember {
mutableStateOf<List<ItemState>>(mutableListOf())
}
val itemsChannel = remember {
Channel<List<ItemState>>(Channel.UNLIMITED)
}
var job: Job? = remember {
null
}
LaunchedEffect(true) {
for (_items in itemsChannel) {
job?.cancel()
job = launch {
withContext(Dispatchers.IO) {
val items = _items.toMutableList()
while (true) {
withFrameMillis {
val iterator = items.iterator()
var index = 0
val itemsToBeRemoved = mutableListOf<ItemState>()
while (iterator.hasNext()) {
val element = iterator.next() //element is ItemState
val elapsedTime = System.nanoTime() - element.startTime
val newX = element.xAnimation.getValueFromNanos(counter)
val newY = element.yAnimation.getValueFromNanos(counter)
items.safeSet(index) {
it.copy(
y = newY,
x = newX,
)
}
index++
if (
itemState.terminalCondition(
newX,
newY
(elapsedTime / 1_000_000).toFloat()
)
) {
itemsToBeRemoved.add(itemState)
}
}
items.removeAll(itemsToBeRemoved)
hearts.value = items.toMutableList()
}
if (hearts.value.isEmpty()) {
job?.cancel()
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment