refactor(android): simplify SavedPostUpdaterWorker

This commit is contained in:
Harsh Shandilya 2022-11-13 12:31:23 +05:30
parent 4a48a2ba4c
commit 28c6f62b81
No known key found for this signature in database

View file

@ -16,11 +16,10 @@ 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.Job
import kotlinx.coroutines.async import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.first
import kotlinx.coroutines.supervisorScope
/** /**
* WorkManager-backed [CoroutineWorker] that gets all the posts from [SavedPostsRepository], fetches * WorkManager-backed [CoroutineWorker] that gets all the posts from [SavedPostsRepository], fetches
@ -28,7 +27,6 @@ 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
@HiltWorker @HiltWorker
class SavedPostUpdaterWorker class SavedPostUpdaterWorker
@AssistedInject @AssistedInject
@ -40,16 +38,18 @@ constructor(
) : CoroutineWorker(appContext, workerParams) { ) : CoroutineWorker(appContext, workerParams) {
override suspend fun doWork(): Result { override suspend fun doWork(): Result {
val posts = savedPostsRepository.savedPosts.first() val posts = savedPostsRepository.savedPosts.first()
posts supervisorScope {
.map { post -> posts
CoroutineScope(coroutineContext + Job()).async { .map { post ->
val details = runCatching { lobstersApi.getPostDetails(post.shortId) }.getOrNull() async {
if (details is ApiResult.Success) { val details = lobstersApi.getPostDetails(post.shortId)
savedPostsRepository.savePost(details.value.toDbModel()) if (details is ApiResult.Success) {
savedPostsRepository.savePost(details.value.toDbModel())
}
} }
} }
} .awaitAll()
.awaitAll() }
return Result.success() return Result.success()
} }
} }