Skip to content

Commit d858a77

Browse files
⚡ optimize: execute shelf synchronization network calls concurrently
Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
1 parent 41e073e commit d858a77

1 file changed

Lines changed: 23 additions & 16 deletions

File tree

app/src/main/java/org/ole/planet/myplanet/services/UploadToShelfService.kt

Lines changed: 23 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,9 @@ import java.util.Date
1313
import javax.inject.Inject
1414
import javax.inject.Singleton
1515
import kotlinx.coroutines.CoroutineScope
16+
import kotlinx.coroutines.async
17+
import kotlinx.coroutines.awaitAll
18+
import kotlinx.coroutines.coroutineScope
1619
import kotlinx.coroutines.launch
1720
import kotlinx.coroutines.withContext
1821
import org.ole.planet.myplanet.callback.OnSuccessListener
@@ -346,22 +349,26 @@ class UploadToShelfService @Inject constructor(
346349
}
347350

348351
try {
349-
unmanagedUsers.forEach { model ->
350-
try {
351-
val jsonDoc = apiInterface.getJsonObject(UrlUtils.header, "${UrlUtils.getUrl()}/shelf/${model._id}").body()
352-
val myLibs = resourcesRepository.getMyLibIds(model.id ?: "")
353-
val myCourseIds = coursesRepository.getMyCourseIds(model.id ?: "")
354-
val shelfData = userRepository.getShelfData(model.id, jsonDoc, myLibs, myCourseIds)
355-
shelfData.addProperty("_rev", getString("_rev", jsonDoc))
356-
apiInterface.putDoc(
357-
UrlUtils.header,
358-
"application/json",
359-
"${UrlUtils.getUrl()}/shelf/${sharedPrefManager.getUserId()}",
360-
shelfData
361-
)
362-
} catch (e: Exception) {
363-
e.printStackTrace()
364-
}
352+
coroutineScope {
353+
unmanagedUsers.map { model ->
354+
async {
355+
try {
356+
val jsonDoc = apiInterface.getJsonObject(UrlUtils.header, "${UrlUtils.getUrl()}/shelf/${model._id}").body()
357+
val myLibs = resourcesRepository.getMyLibIds(model.id ?: "")
358+
val myCourseIds = coursesRepository.getMyCourseIds(model.id ?: "")
359+
val shelfData = userRepository.getShelfData(model.id, jsonDoc, myLibs, myCourseIds)
360+
shelfData.addProperty("_rev", getString("_rev", jsonDoc))
361+
apiInterface.putDoc(
362+
UrlUtils.header,
363+
"application/json",
364+
"${UrlUtils.getUrl()}/shelf/${sharedPrefManager.getUserId()}",
365+
shelfData
366+
)
367+
} catch (e: Exception) {
368+
e.printStackTrace()
369+
}
370+
}
371+
}.awaitAll()
365372
}
366373
withContext(dispatcherProvider.main) {
367374
listener.onSuccess("Sync with server completed successfully")

0 commit comments

Comments
 (0)