android: make SavedPostUpdater more parallel

This commit is contained in:
Harsh Shandilya 2022-04-06 12:41:48 +05:30
parent 27a8d16487
commit 325aca2760
No known key found for this signature in database
GPG key ID: 366D7BBAD1031E80

View file

@ -9,7 +9,11 @@ import dagger.assisted.AssistedInject
import dev.msfjarvis.claw.android.viewmodel.SavedPostsRepository
import dev.msfjarvis.claw.api.LobstersApi
import dev.msfjarvis.claw.common.posts.toDbModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.flow.first
/**
@ -18,6 +22,7 @@ import kotlinx.coroutines.flow.first
* saved posts that were saved before comment counts were added to be able to show a comment count
* and for new-enough posts that are still getting comments to have an accurate one.
*/
@Suppress("DEPRECATION") // We're being nasty
@OptIn(ExperimentalCoroutinesApi::class)
@HiltWorker
class SavedPostUpdaterWorker
@ -29,12 +34,17 @@ constructor(
@Assisted workerParams: WorkerParameters,
) : CoroutineWorker(appContext, workerParams) {
override suspend fun doWork(): Result {
savedPostsRepository
.savedPosts
.first()
.mapNotNull { post -> runCatching { lobstersApi.getPostDetails(post.shortId) }.getOrNull() }
.map { postDetails -> postDetails.toDbModel() }
.map { post -> savedPostsRepository.savePost(post) }
val posts = savedPostsRepository.savedPosts.first()
posts
.map { post ->
CoroutineScope(coroutineContext + Job()).async {
val details = runCatching { lobstersApi.getPostDetails(post.shortId) }.getOrNull()
if (details != null) {
savedPostsRepository.savePost(details.toDbModel())
}
}
}
.awaitAll()
return Result.success()
}
}