so I'm new to kotlin, and I'm trying to do a api call to an image api endpoint and download all the images at one and make the user wait until all images is downloaded so all can be displayed at once.
dataclass
@Serializable
data class RandomPhotosItem(
val author: String,
@SerialName(value = "download_url")
val downloadURL: String,
val height: Int,
val id: String,
val url: String,
val width: Int
)
I'm downloading all the download_urls then sending them to another api call where I download all the images and i want to do this at the same time, the problem is that my app is crashing because I'm overloading the threads i guess..
object MarsApi {
val retrofitService: MarsApiService by lazy {
retrofit.create(MarsApiService::class.java)
}
val retroFitServ: DownloadPhotosApiService by lazy {
retrofit.create(DownloadPhotosApiService::class.java)
}
}
public interface DownloadPhotosApiService{
@GET("")
suspend fun downloadImages(@Url myUrls: String) : ResponseBody
}
And this is the code where i call on the api and store the images to my array.
suspend fun fetchImages(urls: ArrayList<RandomPhotosItem>): MutableList<Bitmap> {
val myUrls = urls.map { it.downloadURL }
val results = mutableListOf<Bitmap>()
try {
coroutineScope {
val tasks = List(urls.size) { index -> // Drar igång hela url listans
async(Dispatchers.IO) {
performTask(myUrls[index])
}
}
tasks.forEach {
val inputStream = it.await()
//val bitmap = BitmapFactory.decodeStream(inputStream)
val bitmap = decodeStream(inputStream)
inputStream.close()
if (bitmap != null) {
results.add(bitmap)
}
}
}
} catch (e: Exception) {
}
return results
}
suspend fun performTask(myUrls: String): InputStream {
val response = MarsApi.retroFitServ.downloadImages(myUrls)
return response.byteStream()
}
Maybe if i change so the sizes of the images are smaller to save memory? The app works on my desktop computer, sure its slow and it feels like the app has frozen but it works. on my laptop it just crashes..
would appreciate help, been trying to fix this for 3 days now, thank you.
I've tried limiting the amount of images being downloaded at the same time, I've changed between ByteArray to byteStream and transform this to Bitmap.
I just want the app not to crash and that the app loads all 30 images.