Reputation: 1298
I have a list of a model of mine called GroupMemberEntity.
I want to set that list into my collection, each one getting its own unique ID using UUID.
My current implementation is the following -
suspend fun addGroupMembers(
groupId: String,
users: List<GroupMemberEntity>
) = suspendCoroutine<ResponseHandler.Resource<Any>> { continuation ->
var insertCounter = 1
users.forEach { entity ->
FIRESTORE_DATABASE.collection(ACTIVITIES_COLLECTION)
.document(UUID.randomUUID().toString())
.set(entity)
.addOnSuccessListener {
insertCounter++
if (insertCounter != users.size) return@addOnSuccessListener
continuation.resume(responseHandler.handleSuccess())
}
.addOnFailureListener { exception ->
continuation.resume(responseHandler.handleException(exception))
}
}
}
I have a feeling this can be improved by not using the forEach
loop, but I'm not sure how. doing a network call in a loop seems like a bad idea in general.
Any advice would be helpful.
Upvotes: 0
Views: 618
Reputation: 4712
If you want each entity to have its own document, than you need to use the for-each
approach:
suspend fun addGroupMember(groupId: String, user: List<GroupMemberEntity>) {
users.forEach {
FIRESTORE_DATABASE.collection(ACTIVITIES_COLLECTION)
.document(UUID.randomUUID().toString())
.set(entity)
.await()
}
}
Another, maybe easier approach would be to just post the entire list in one document. You can later retrieve or (I think) query within this document for a specific field. For this, I would add a uuid
to your GroupMemberEntity
. But I am not 100% sure if this works.
Upvotes: 1