'Building a list in a loop - avoid using MutableList

Is there a way I can build a list without using MutableList when I need to call a api synchronously in a loop? I need to call the api synchronously because the response is paged.. so I get 10 results back per response, then I request the next page. Although, having said that, after the first request I know exactly how many pages there are (in the response I get totalPages) so I could theoretically make async requests for the remaining data

The code below works - but can I do the same thing more elegantly? Possibly using async FP, without vars and a MutableList

  private fun getAllCustomers(): List<Customer> {
    var pageNumber = 0
    var totalPages = 1
    val allCustomers: MutableList<Customer> = mutableListOf()
    while (pageNumber < totalPages) {
      val response = customerApi.getCustomers(alphaChar, pageNumber)
      totalPages = response.totalPages
      pageNumber ++
      allCustomers.addAll(response.content)
    }
    return allCustomers
  }


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source