Skip to content

Commit 267adfd

Browse files
authored
Batch sync news resources from remote
Batch sync news resources from remote to reduce json payload size.
1 parent 0844d02 commit 267adfd

File tree

1 file changed

+23
-18
lines changed

1 file changed

+23
-18
lines changed

core/data/src/main/java/com/google/samples/apps/nowinandroid/core/data/repository/OfflineFirstNewsRepository.kt

Lines changed: 23 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@ import kotlinx.coroutines.flow.Flow
3434
import kotlinx.coroutines.flow.map
3535
import javax.inject.Inject
3636

37+
private const val SYNC_BATCH_SIZE = 40
38+
3739
/**
3840
* Disk storage backed implementation of the [NewsRepository].
3941
* Reads are exclusively from local storage to support offline access.
@@ -65,26 +67,29 @@ class OfflineFirstNewsRepository @Inject constructor(
6567
},
6668
modelDeleter = newsResourceDao::deleteNewsResources,
6769
modelUpdater = { changedIds ->
68-
val networkNewsResources = network.getNewsResources(ids = changedIds)
70+
changedIds.chunked(SYNC_BATCH_SIZE).forEach { chunkedIds
71+
val networkNewsResources = network.getNewsResources(ids = chunkedIds)
6972

70-
// Order of invocation matters to satisfy id and foreign key constraints!
73+
// Order of invocation matters to satisfy id and foreign key constraints!
7174

72-
topicDao.insertOrIgnoreTopics(
73-
topicEntities = networkNewsResources
74-
.map(NetworkNewsResource::topicEntityShells)
75-
.flatten()
76-
.distinctBy(TopicEntity::id),
77-
)
78-
newsResourceDao.upsertNewsResources(
79-
newsResourceEntities = networkNewsResources
80-
.map(NetworkNewsResource::asEntity),
81-
)
82-
newsResourceDao.insertOrIgnoreTopicCrossRefEntities(
83-
newsResourceTopicCrossReferences = networkNewsResources
84-
.map(NetworkNewsResource::topicCrossReferences)
85-
.distinct()
86-
.flatten(),
87-
)
75+
topicDao.insertOrIgnoreTopics(
76+
topicEntities = networkNewsResources
77+
.map(NetworkNewsResource::topicEntityShells)
78+
.flatten()
79+
.distinctBy(TopicEntity::id),
80+
)
81+
newsResourceDao.upsertNewsResources(
82+
newsResourceEntities = networkNewsResources.map(
83+
NetworkNewsResource::asEntity
84+
),
85+
)
86+
newsResourceDao.insertOrIgnoreTopicCrossRefEntities(
87+
newsResourceTopicCrossReferences = networkNewsResources
88+
.map(NetworkNewsResource::topicCrossReferences)
89+
.distinct()
90+
.flatten(),
91+
)
92+
}
8893
},
8994
)
9095
}

0 commit comments

Comments
 (0)