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.api.LobstersApi
import dev.msfjarvis.claw.common.posts.toDbModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.supervisorScope
/**
* 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
* and for new-enough posts that are still getting comments to have an accurate one.
*/
@Suppress("DEPRECATION") // We're being nasty
@HiltWorker
class SavedPostUpdaterWorker
@AssistedInject
@ -40,16 +38,18 @@ constructor(
) : CoroutineWorker(appContext, workerParams) {
override suspend fun doWork(): Result {
val posts = savedPostsRepository.savedPosts.first()
posts
.map { post ->
CoroutineScope(coroutineContext + Job()).async {
val details = runCatching { lobstersApi.getPostDetails(post.shortId) }.getOrNull()
if (details is ApiResult.Success) {
savedPostsRepository.savePost(details.value.toDbModel())
supervisorScope {
posts
.map { post ->
async {
val details = lobstersApi.getPostDetails(post.shortId)
if (details is ApiResult.Success) {
savedPostsRepository.savePost(details.value.toDbModel())
}
}
}
}
.awaitAll()
.awaitAll()
}
return Result.success()
}
}