mirror of
https://github.com/msfjarvis/compose-lobsters
synced 2025-08-14 08:17:04 +05:30
android: make SavedPostUpdater more parallel
This commit is contained in:
parent
27a8d16487
commit
325aca2760
1 changed files with 16 additions and 6 deletions
|
@ -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()
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue