Skip to content

Commit 214b1d2

Browse files
⚡ optimize: execute shelf synchronization network calls concurrently
- Fixes sequential N+1 network call scaling by executing user API PUTs concurrently inside a coroutineScope using `async` and `.awaitAll()`. - Fixes pre-existing logical bug where data was being incorrectly pushed to the logged-in user's shelf URL instead of the respective model's URL (`model._id`). - Implements a `.chunked(10)` concurrency limit to prevent connection pool exhaustion and overwhelming the server. Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
1 parent d858a77 commit 214b1d2

1 file changed

Lines changed: 20 additions & 18 deletions

File tree

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

Lines changed: 20 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -350,25 +350,27 @@ class UploadToShelfService @Inject constructor(
350350

351351
try {
352352
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()
353+
unmanagedUsers.chunked(10).forEach { chunk ->
354+
chunk.map { model ->
355+
async {
356+
try {
357+
val jsonDoc = apiInterface.getJsonObject(UrlUtils.header, "${UrlUtils.getUrl()}/shelf/${model._id}").body()
358+
val myLibs = resourcesRepository.getMyLibIds(model.id ?: "")
359+
val myCourseIds = coursesRepository.getMyCourseIds(model.id ?: "")
360+
val shelfData = userRepository.getShelfData(model.id, jsonDoc, myLibs, myCourseIds)
361+
shelfData.addProperty("_rev", getString("_rev", jsonDoc))
362+
apiInterface.putDoc(
363+
UrlUtils.header,
364+
"application/json",
365+
"${UrlUtils.getUrl()}/shelf/${model._id}",
366+
shelfData
367+
)
368+
} catch (e: Exception) {
369+
e.printStackTrace()
370+
}
369371
}
370-
}
371-
}.awaitAll()
372+
}.awaitAll()
373+
}
372374
}
373375
withContext(dispatcherProvider.main) {
374376
listener.onSuccess("Sync with server completed successfully")

0 commit comments

Comments
 (0)