Ho to make this call async ```videosList.forEachIn...
# coroutines
k
Ho to make this call async
Copy code
videosList.forEachIndexed { index, video: BaseVideo ->
            val userData = getUserData(video)*//calling suspend function* 
            listWithData[index].userData = userData
        }
g
Copy code
val result: List<UserData> = videosList.map { video ->
   async { getUserData(video) }
}.awaitAll()
But in this case you do not limit concurrency
k
"But in this case you do not limit concurrency" h
What does this mean , please explain
g
it means that each item of videosList will start own coroutine
it may be fine
depends on what getUserData does
k
so does it effect perfomance
?
coroutine itself is cheap.
k
getUserData just get Document from Firestore collection
g
don’t know how it works, so have no advices
just mention that it doesn’t limit concurrency
if you want limit amount of concurrent coroutines you need working pool pattern implementation
I recommend you watch this talk from KotlinConf by Roman

https://www.youtube.com/watch?v=a3agLJQ6vt8

👍 1
k
Yes, thanks for link, i will definitely check it out
g
Actually, in your case you have also simple way to limit amount of parallel tasks, just use chunked:
Copy code
val result: List<UserData> = videosList.chunked(PARALLEL_COROUTINES_AMOUNT).flatMap { videos -> 
   videos.map { video ->
        async { getUserData(video) }
    }.awaitAll()
}
k
But here i know in advance that how many items
videosList
is having , it has only 5 items ,so i don't think i have to convert it to
chucked
. i'm paginating
RecyclerView
loading data 5 items each time
g
Then don’t worry about concurrency
k
But still i think that what would happen if user scrolls list lot of time ,then there will be many
async
coroutines
created ,so how much it will effect ?
g
as I said, it depends on getUserData implementation
k
Copy code
private suspend fun getUserData(video: BaseVideo): UserDataAboutVideo? {
        return if (currentUser != null) {
            val userDataDocument = firestore.getUserDataAboutVideos(currentUser!!.uid)
                    .document(video.videoId).get().await()

            if (userDataDocument.exists())
                userDataDocument.toObject(UserDataAboutVideo::class.java)!!
            else
                null

        } else null
    }
await implementation is
Copy code
suspend fun <T> Task<T>.await(): T {
    return suspendCoroutine { continuation ->
        this.addOnCompleteListener { result ->
            if (result.result != null && result.isSuccessful)
                continuation.resume(result.result!!)
            else
                continuation.resumeWithException(result.exception?.cause!!)
        }
    }
}
g
I have no idea how Firestore is implemented and work with multiple parallel requests
k
ok, No problem, thanks for your all suggestions 👍
your answers helped me alot
g
👍