https://kotlinlang.org logo
#getting-started
Title
# getting-started
z

zt

03/20/2024, 4:52 AM
I have a problem I'm struggling to plan out Things have been simplified but the basic idea is the same I have an API that returns a list of IDs and their corresponding type: a, b and c To get more information on the specific object I can use the API to request more information but only the specific endpoint for that type Additionally I can batch request at most 50 IDs for a type Now how would I take this list of objects and create a new list that has the additional information while preserving order and doing it in the least amount of time using kotlin, maybe with flows
s

Sam

03/20/2024, 8:48 AM
For preserving the order, one trick you could try is using
withIndex()
on your original list of objects. That will tag each one with its position in the original list. Then you can group and process the elements however you want, storing this "original index" alongside each item as you go. Once you have all your results, you can use that stored index to reconstruct the original list order.
Something like this:
Copy code
fun getResults(inputs: List<Input>): List<Output> {
  val outputs = arrayOfNulls<Output>(inputs.size)

  val inputsByType: Map<Input.Type, List<IndexedValue<Input>>> =
    inputs.withIndex().groupBy { it.value.type }

  for ((type, items) in inputsByType) {
    for (batch in items.chunked(batchSize)) {
      val results = api.getItemBatch(type, batch.map { it.value })
      for ((request, result) in batch zip results) {
        outputs[request.index] = result
      }
    }
  }

  return outputs.requireNoNulls().asList()
}
Making
outputs
an
Array
means it should even be safe to add concurrency if you want
Don't believe the lies; arrays are thread safe 😄