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