A fully functional Android app built entirely with Kotlin and Jetpack Compose
Backend triggered sync
Adetunji Dahunsi08956492c84e
diff --git a/core/data/build.gradle.kts b/core/data/build.gradle.ktsindex e4b265649..5d34aac2c 100644--- a/core/data/build.gradle.kts+++ b/core/data/build.gradle.kts@@ -36,6 +36,7 @@ dependencies {implementation(project(":core:datastore"))implementation(project(":core:model"))implementation(project(":core:network"))+ implementation(project(":core:notifications"))implementation(libs.androidx.core.ktx)implementation(libs.kotlinx.coroutines.android)implementation(libs.kotlinx.datetime)diff --git a/core/data/src/main/java/com/google/samples/apps/nowinandroid/core/data/repository/OfflineFirstNewsRepository.kt b/core/data/src/main/java/com/google/samples/apps/nowinandroid/core/data/repository/OfflineFirstNewsRepository.ktindex c16355d69..02c58d855 100644--- a/core/data/src/main/java/com/google/samples/apps/nowinandroid/core/data/repository/OfflineFirstNewsRepository.kt+++ b/core/data/src/main/java/com/google/samples/apps/nowinandroid/core/data/repository/OfflineFirstNewsRepository.kt@@ -30,7 +30,9 @@ import com.google.samples.apps.nowinandroid.core.datastore.ChangeListVersionsimport com.google.samples.apps.nowinandroid.core.model.data.NewsResourceimport com.google.samples.apps.nowinandroid.core.network.NiaNetworkDataSourceimport com.google.samples.apps.nowinandroid.core.network.model.NetworkNewsResource+import com.google.samples.apps.nowinandroid.core.notifications.Notifierimport kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.firstimport kotlinx.coroutines.flow.mapimport javax.inject.Inject@@ -46,6 +48,7 @@ class OfflineFirstNewsRepository @Inject constructor(private val newsResourceDao: NewsResourceDao,private val topicDao: TopicDao,private val network: NiaNetworkDataSource,+ private val notifier: Notifier,) : NewsRepository {override fun getNewsResources(@@ -69,6 +72,16 @@ class OfflineFirstNewsRepository @Inject constructor(},modelDeleter = newsResourceDao::deleteNewsResources,modelUpdater = { changedIds ->+ // TODO: Make this more efficient, there is no need to retrieve populated+ // news resources when all that's needed are the ids+ val existingNewsResourceIds = newsResourceDao.getNewsResources(+ useFilterNewsIds = true,+ filterNewsIds = changedIds.toSet(),+ )+ .first()+ .map { it.entity.id }+ .toSet()+changedIds.chunked(SYNC_BATCH_SIZE).forEach { chunkedIds ->val networkNewsResources = network.getNewsResources(ids = chunkedIds)@@ -92,6 +105,20 @@ class OfflineFirstNewsRepository @Inject constructor(.flatten(),)}++ val addedNewsResources = newsResourceDao.getNewsResources(+ useFilterNewsIds = true,+ filterNewsIds = changedIds.toSet(),+ )+ .first()+ .filter { !existingNewsResourceIds.contains(it.entity.id) }+ .map(PopulatedNewsResource::asExternalModel)++ // TODO: Define business logic for notifications on first time sync.+ // we probably do not want to send notifications on first install.+ // We can easily check if the change list version is 0 and not send notifications+ // if it is.+ if (addedNewsResources.isNotEmpty()) notifier.onNewsAdded(addedNewsResources)},)}diff --git a/core/data/src/main/java/com/google/samples/apps/nowinandroid/core/data/util/SyncStatusMonitor.kt b/core/data/src/main/java/com/google/samples/apps/nowinandroid/core/data/util/SyncManager.ktsimilarity index 94%rename from core/data/src/main/java/com/google/samples/apps/nowinandroid/core/data/util/SyncStatusMonitor.ktrename to core/data/src/main/java/com/google/samples/apps/nowinandroid/core/data/util/SyncManager.ktindex 14823ed0e..d72fa27a6 100644--- a/core/data/src/main/java/com/google/samples/apps/nowinandroid/core/data/util/SyncStatusMonitor.kt+++ b/core/data/src/main/java/com/google/samples/apps/nowinandroid/core/data/util/SyncManager.kt@@ -21,6 +21,7 @@ import kotlinx.coroutines.flow.Flow/*** Reports on if synchronization is in progress*/-interface SyncStatusMonitor {+interface SyncManager {val isSyncing: Flow<Boolean>+ fun requestSync()}diff --git a/core/data/src/test/java/com/google/samples/apps/nowinandroid/core/data/repository/OfflineFirstNewsRepositoryTest.kt b/core/data/src/test/java/com/google/samples/apps/nowinandroid/core/data/repository/OfflineFirstNewsRepositoryTest.ktindex 6b424e69e..6cdbf67d0 100644--- a/core/data/src/test/java/com/google/samples/apps/nowinandroid/core/data/repository/OfflineFirstNewsRepositoryTest.kt+++ b/core/data/src/test/java/com/google/samples/apps/nowinandroid/core/data/repository/OfflineFirstNewsRepositoryTest.kt@@ -36,6 +36,7 @@ import com.google.samples.apps.nowinandroid.core.datastore.test.testUserPreferenimport com.google.samples.apps.nowinandroid.core.model.data.NewsResourceimport com.google.samples.apps.nowinandroid.core.network.model.NetworkChangeListimport com.google.samples.apps.nowinandroid.core.network.model.NetworkNewsResource+import com.google.samples.apps.nowinandroid.core.testing.notifications.TestNotifierimport kotlinx.coroutines.flow.firstimport kotlinx.coroutines.test.TestScopeimport kotlinx.coroutines.test.UnconfinedTestDispatcher@@ -58,6 +59,8 @@ class OfflineFirstNewsRepositoryTest {private lateinit var network: TestNiaNetworkDataSource+ private lateinit var notifier: TestNotifier+private lateinit var synchronizer: Synchronizer@get:Rule@@ -68,6 +71,7 @@ class OfflineFirstNewsRepositoryTest {newsResourceDao = TestNewsResourceDao()topicDao = TestTopicDao()network = TestNiaNetworkDataSource()+ notifier = TestNotifier()synchronizer = TestSynchronizer(NiaPreferencesDataSource(tmpFolder.testUserPreferencesDataStore(testScope),@@ -78,6 +82,7 @@ class OfflineFirstNewsRepositoryTest {newsResourceDao = newsResourceDao,topicDao = topicDao,network = network,+ notifier = notifier,)}@@ -145,6 +150,12 @@ class OfflineFirstNewsRepositoryTest {expected = network.latestChangeListVersion(CollectionType.NewsResources),actual = synchronizer.getChangeListVersions().newsResourceVersion,)++ // Notifier should have been called with new news resources+ assertEquals(+ expected = newsResourcesFromDb.map(NewsResource::id).sorted(),+ actual = notifier.addedNewsResources.first().map(NewsResource::id).sorted(),+ )}@Test@@ -186,6 +197,13 @@ class OfflineFirstNewsRepositoryTest {expected = network.latestChangeListVersion(CollectionType.NewsResources),actual = synchronizer.getChangeListVersions().newsResourceVersion,)++ // Notifier should have been called with news resources from network that are not+ // deleted+ assertEquals(+ expected = (newsResourcesFromNetwork.map(NewsResource::id) - deletedItems).sorted(),+ actual = notifier.addedNewsResources.first().map(NewsResource::id).sorted(),+ )}@Test@@ -225,6 +243,12 @@ class OfflineFirstNewsRepositoryTest {expected = changeList.last().changeListVersion,actual = synchronizer.getChangeListVersions().newsResourceVersion,)++ // Notifier should have been called with only added news resources from network+ assertEquals(+ expected = newsResourcesFromNetwork.map(NewsResource::id).sorted(),+ actual = notifier.addedNewsResources.first().map(NewsResource::id).sorted(),+ )}@Testdiff --git a/core/notifications/.gitignore b/core/notifications/.gitignorenew file mode 100644index 000000000..42afabfd2--- /dev/null+++ b/core/notifications/.gitignore@@ -0,0 +1 @@+/build\ No newline at end of filediff --git a/core/notifications/build.gradle.kts b/core/notifications/build.gradle.ktsnew file mode 100644index 000000000..608e59a38--- /dev/null+++ b/core/notifications/build.gradle.kts@@ -0,0 +1,35 @@+/*+ * Copyright 2023 The Android Open Source Project+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+plugins {+ id("nowinandroid.android.library")+ id("nowinandroid.android.library.compose")+ id("nowinandroid.android.hilt")+}++android {+ namespace = "com.google.samples.apps.nowinandroid.core.notifications"+}++dependencies {+ implementation(project(":core:model"))++ implementation(libs.kotlinx.coroutines.android)+ implementation(libs.androidx.compose.runtime)+ implementation(libs.androidx.core.ktx)++ implementation(platform(libs.firebase.bom))+ implementation(libs.firebase.cloud.messaging)+}diff --git a/core/notifications/src/demo/java/com/google/samples/apps/nowinandroid/core/notifications/NotificationsModule.kt b/core/notifications/src/demo/java/com/google/samples/apps/nowinandroid/core/notifications/NotificationsModule.ktnew file mode 100644index 000000000..9bb2b3fb9--- /dev/null+++ b/core/notifications/src/demo/java/com/google/samples/apps/nowinandroid/core/notifications/NotificationsModule.kt@@ -0,0 +1,31 @@+/*+ * Copyright 2023 The Android Open Source Project+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package com.google.samples.apps.nowinandroid.core.notifications++import dagger.Binds+import dagger.Module+import dagger.hilt.InstallIn+import dagger.hilt.components.SingletonComponent++@Module+@InstallIn(SingletonComponent::class)+abstract class NotificationsModule {+ @Binds+ abstract fun bindNotifier(+ notifier: NoOpNotifier,+ ): Notifier+}diff --git a/core/notifications/src/main/AndroidManifest.xml b/core/notifications/src/main/AndroidManifest.xmlnew file mode 100644index 000000000..31c889874--- /dev/null+++ b/core/notifications/src/main/AndroidManifest.xml@@ -0,0 +1,17 @@+<?xml version="1.0" encoding="utf-8"?>+<!--+ Copyright 2023 The Android Open Source Project++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.+-->+<manifest xmlns:android="http://schemas.android.com/apk/res/android"/>diff --git a/core/notifications/src/main/java/com/google/samples/apps/nowinandroid/core/notifications/AndroidSystemNotifier.kt b/core/notifications/src/main/java/com/google/samples/apps/nowinandroid/core/notifications/AndroidSystemNotifier.ktnew file mode 100644index 000000000..00d97fcb3--- /dev/null+++ b/core/notifications/src/main/java/com/google/samples/apps/nowinandroid/core/notifications/AndroidSystemNotifier.kt@@ -0,0 +1,32 @@+/*+ * Copyright 2023 The Android Open Source Project+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package com.google.samples.apps.nowinandroid.core.notifications++import com.google.samples.apps.nowinandroid.core.model.data.NewsResource+import javax.inject.Inject+import javax.inject.Singleton++/**+ * Implementation of [Notifier] that displays notifications in the system tray.+ */+@Singleton+class AndroidSystemNotifier @Inject constructor() : Notifier {++ override fun onNewsAdded(newsResources: List<NewsResource>) {+ // TODO, create notification and display to the user+ }+}diff --git a/core/notifications/src/main/java/com/google/samples/apps/nowinandroid/core/notifications/NoOpNotifier.kt b/core/notifications/src/main/java/com/google/samples/apps/nowinandroid/core/notifications/NoOpNotifier.ktnew file mode 100644index 000000000..5a8141e91--- /dev/null+++ b/core/notifications/src/main/java/com/google/samples/apps/nowinandroid/core/notifications/NoOpNotifier.kt@@ -0,0 +1,27 @@+/*+ * Copyright 2023 The Android Open Source Project+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package com.google.samples.apps.nowinandroid.core.notifications++import com.google.samples.apps.nowinandroid.core.model.data.NewsResource+import javax.inject.Inject++/**+ * Implementation of [Notifier] which does nothing. Useful for tests and previews.+ */+class NoOpNotifier @Inject constructor() : Notifier {+ override fun onNewsAdded(newsResources: List<NewsResource>) = Unit+}diff --git a/core/notifications/src/main/java/com/google/samples/apps/nowinandroid/core/notifications/Notifier.kt b/core/notifications/src/main/java/com/google/samples/apps/nowinandroid/core/notifications/Notifier.ktnew file mode 100644index 000000000..3084dcb75--- /dev/null+++ b/core/notifications/src/main/java/com/google/samples/apps/nowinandroid/core/notifications/Notifier.kt@@ -0,0 +1,26 @@+/*+ * Copyright 2023 The Android Open Source Project+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package com.google.samples.apps.nowinandroid.core.notifications++import com.google.samples.apps.nowinandroid.core.model.data.NewsResource++/**+ * Interface for creating notifications in the app+ */+interface Notifier {+ fun onNewsAdded(newsResources: List<NewsResource>)+}diff --git a/core/notifications/src/main/res/values/strings.xml b/core/notifications/src/main/res/values/strings.xmlnew file mode 100644index 000000000..e3fd73ff8--- /dev/null+++ b/core/notifications/src/main/res/values/strings.xml@@ -0,0 +1,22 @@+<?xml version="1.0" encoding="utf-8"?>+<!--+ Copyright 2022 The Android Open Source Project++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.+-->+<resources>+ <string name="sync_notification_title">Now in Android</string>+ <string name="sync_notification_channel_name">Sync</string>+ <string name="sync_notification_channel_description">Background tasks for Now in Android</string>++</resources>diff --git a/core/notifications/src/prod/java/com/google/samples/apps/nowinandroid/core/notifications/NotificationsModule.kt b/core/notifications/src/prod/java/com/google/samples/apps/nowinandroid/core/notifications/NotificationsModule.ktnew file mode 100644index 000000000..0b4bd6bae--- /dev/null+++ b/core/notifications/src/prod/java/com/google/samples/apps/nowinandroid/core/notifications/NotificationsModule.kt@@ -0,0 +1,31 @@+/*+ * Copyright 2023 The Android Open Source Project+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package com.google.samples.apps.nowinandroid.core.notifications++import dagger.Binds+import dagger.Module+import dagger.hilt.InstallIn+import dagger.hilt.components.SingletonComponent++@Module+@InstallIn(SingletonComponent::class)+abstract class NotificationsModule {+ @Binds+ abstract fun bindNotifier(+ notifier: AndroidSystemNotifier,+ ): Notifier+}diff --git a/core/testing/build.gradle.kts b/core/testing/build.gradle.ktsindex 4e87bb039..2fea5beb3 100644--- a/core/testing/build.gradle.kts+++ b/core/testing/build.gradle.kts@@ -40,5 +40,6 @@ dependencies {implementation(project(":core:data"))implementation(project(":core:domain"))implementation(project(":core:model"))+ implementation(project(":core:notifications"))implementation(libs.kotlinx.datetime)}diff --git a/core/testing/src/main/java/com/google/samples/apps/nowinandroid/core/testing/notifications/TestNotifier.kt b/core/testing/src/main/java/com/google/samples/apps/nowinandroid/core/testing/notifications/TestNotifier.ktnew file mode 100644index 000000000..669d2e6c4--- /dev/null+++ b/core/testing/src/main/java/com/google/samples/apps/nowinandroid/core/testing/notifications/TestNotifier.kt@@ -0,0 +1,34 @@+/*+ * Copyright 2023 The Android Open Source Project+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package com.google.samples.apps.nowinandroid.core.testing.notifications++import com.google.samples.apps.nowinandroid.core.model.data.NewsResource+import com.google.samples.apps.nowinandroid.core.notifications.Notifier++/**+ * Aggregates news resources that have been notified for addition+ */+class TestNotifier : Notifier {++ private val mutableAddedNewResources = mutableListOf<List<NewsResource>>()++ val addedNewsResources: List<List<NewsResource>> = mutableAddedNewResources++ override fun onNewsAdded(newsResources: List<NewsResource>) {+ mutableAddedNewResources.add(newsResources)+ }+}diff --git a/core/testing/src/main/java/com/google/samples/apps/nowinandroid/core/testing/util/TestSyncStatusMonitor.kt b/core/testing/src/main/java/com/google/samples/apps/nowinandroid/core/testing/util/TestSyncManager.ktsimilarity index 85%rename from core/testing/src/main/java/com/google/samples/apps/nowinandroid/core/testing/util/TestSyncStatusMonitor.ktrename to core/testing/src/main/java/com/google/samples/apps/nowinandroid/core/testing/util/TestSyncManager.ktindex a2edc89ff..999b67195 100644--- a/core/testing/src/main/java/com/google/samples/apps/nowinandroid/core/testing/util/TestSyncStatusMonitor.kt+++ b/core/testing/src/main/java/com/google/samples/apps/nowinandroid/core/testing/util/TestSyncManager.kt@@ -16,16 +16,20 @@package com.google.samples.apps.nowinandroid.core.testing.util-import com.google.samples.apps.nowinandroid.core.data.util.SyncStatusMonitor+import com.google.samples.apps.nowinandroid.core.data.util.SyncManagerimport kotlinx.coroutines.flow.Flowimport kotlinx.coroutines.flow.MutableStateFlow-class TestSyncStatusMonitor : SyncStatusMonitor {+class TestSyncManager : SyncManager {private val syncStatusFlow = MutableStateFlow(false)override val isSyncing: Flow<Boolean> = syncStatusFlow+ override fun requestSync() {+ TODO("Not yet implemented")+ }+/*** A test-only API to set the sync status from tests.*/diff --git a/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModel.kt b/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModel.ktindex 085593932..376624376 100644--- a/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModel.kt+++ b/feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModel.kt@@ -20,7 +20,7 @@ import androidx.lifecycle.ViewModelimport androidx.lifecycle.viewModelScopeimport com.google.samples.apps.nowinandroid.core.data.repository.NewsResourceQueryimport com.google.samples.apps.nowinandroid.core.data.repository.UserDataRepository-import com.google.samples.apps.nowinandroid.core.data.util.SyncStatusMonitor+import com.google.samples.apps.nowinandroid.core.data.util.SyncManagerimport com.google.samples.apps.nowinandroid.core.domain.GetFollowableTopicsUseCaseimport com.google.samples.apps.nowinandroid.core.domain.GetUserNewsResourcesUseCaseimport com.google.samples.apps.nowinandroid.core.domain.model.UserNewsResource@@ -41,7 +41,7 @@ import javax.inject.Inject@HiltViewModelclass ForYouViewModel @Inject constructor(- syncStatusMonitor: SyncStatusMonitor,+ syncManager: SyncManager,private val userDataRepository: UserDataRepository,getUserNewsResources: GetUserNewsResourcesUseCase,getFollowableTopics: GetFollowableTopicsUseCase,@@ -50,7 +50,7 @@ class ForYouViewModel @Inject constructor(private val shouldShowOnboarding: Flow<Boolean> =userDataRepository.userData.map { !it.shouldHideOnboarding }- val isSyncing = syncStatusMonitor.isSyncing+ val isSyncing = syncManager.isSyncing.stateIn(scope = viewModelScope,started = SharingStarted.WhileSubscribed(5_000),diff --git a/feature/foryou/src/test/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModelTest.kt b/feature/foryou/src/test/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModelTest.ktindex 9e51758f0..db8178b89 100644--- a/feature/foryou/src/test/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModelTest.kt+++ b/feature/foryou/src/test/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModelTest.kt@@ -30,7 +30,7 @@ import com.google.samples.apps.nowinandroid.core.testing.repository.TestUserDataimport com.google.samples.apps.nowinandroid.core.testing.repository.emptyUserDataimport com.google.samples.apps.nowinandroid.core.testing.util.MainDispatcherRuleimport com.google.samples.apps.nowinandroid.core.testing.util.TestNetworkMonitor-import com.google.samples.apps.nowinandroid.core.testing.util.TestSyncStatusMonitor+import com.google.samples.apps.nowinandroid.core.testing.util.TestSyncManagerimport com.google.samples.apps.nowinandroid.core.ui.NewsFeedUiStateimport kotlinx.coroutines.flow.collectimport kotlinx.coroutines.launch@@ -52,7 +52,7 @@ class ForYouViewModelTest {val mainDispatcherRule = MainDispatcherRule()private val networkMonitor = TestNetworkMonitor()- private val syncStatusMonitor = TestSyncStatusMonitor()+ private val syncManager = TestSyncManager()private val userDataRepository = TestUserDataRepository()private val topicsRepository = TestTopicsRepository()private val newsRepository = TestNewsRepository()@@ -70,7 +70,7 @@ class ForYouViewModelTest {@Beforefun setup() {viewModel = ForYouViewModel(- syncStatusMonitor = syncStatusMonitor,+ syncManager = syncManager,userDataRepository = userDataRepository,getUserNewsResources = getUserNewsResourcesUseCase,getFollowableTopics = getFollowableTopicsUseCase,@@ -106,7 +106,7 @@ class ForYouViewModelTest {@Testfun stateIsLoadingWhenAppIsSyncingWithNoInterests() = runTest {- syncStatusMonitor.setSyncing(true)+ syncManager.setSyncing(true)val collectJob =launch(UnconfinedTestDispatcher()) { viewModel.isSyncing.collect() }diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex 737ad43a0..8826089a8 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -94,19 +94,20 @@ androidx-test-ext = { group = "androidx.test.ext", name = "junit-ktx", version.randroidx-test-rules = { group = "androidx.test", name = "rules", version.ref = "androidxTestRules" }androidx-test-runner = { group = "androidx.test", name = "runner", version.ref = "androidxTestRunner" }androidx-test-uiautomator = { group = "androidx.test.uiautomator", name = "uiautomator", version.ref = "androidxUiAutomator" }-androidx-tracing-ktx = { group = "androidx.tracing", name="tracing-ktx", version.ref = "androidxTracing" }+androidx-tracing-ktx = { group = "androidx.tracing", name = "tracing-ktx", version.ref = "androidxTracing" }androidx-window-manager = { module = "androidx.window:window", version.ref = "androidxWindowManager" }androidx-work-ktx = { group = "androidx.work", name = "work-runtime-ktx", version.ref = "androidxWork" }androidx-work-testing = { group = "androidx.work", name = "work-testing", version.ref = "androidxWork" }coil-kt = { group = "io.coil-kt", name = "coil", version.ref = "coil" }coil-kt-compose = { group = "io.coil-kt", name = "coil-compose", version.ref = "coil" }coil-kt-svg = { group = "io.coil-kt", name = "coil-svg", version.ref = "coil" }-firebase-bom = { group = "com.google.firebase", name = "firebase-bom", version.ref="firebaseBom"}-firebase-analytics = { group = "com.google.firebase", name = "firebase-analytics-ktx"}-firebase-crashlytics = { group = "com.google.firebase", name = "firebase-crashlytics-ktx"}-firebase-crashlytics-gradle = { group = "com.google.firebase", name="firebase-crashlytics-gradle", version.ref = "firebaseCrashlyticsPlugin"}-firebase-performance = { group = "com.google.firebase", name = "firebase-perf-ktx"}-firebase-performance-gradle = { group = "com.google.firebase", name = "perf-plugin", version.ref = "firebasePerfPlugin"}+firebase-bom = { group = "com.google.firebase", name = "firebase-bom", version.ref = "firebaseBom" }+firebase-analytics = { group = "com.google.firebase", name = "firebase-analytics-ktx" }+firebase-cloud-messaging = { group = "com.google.firebase", name = "firebase-messaging-ktx" }+firebase-crashlytics = { group = "com.google.firebase", name = "firebase-crashlytics-ktx" }+firebase-crashlytics-gradle = { group = "com.google.firebase", name = "firebase-crashlytics-gradle", version.ref = "firebaseCrashlyticsPlugin" }+firebase-performance = { group = "com.google.firebase", name = "firebase-perf-ktx" }+firebase-performance-gradle = { group = "com.google.firebase", name = "perf-plugin", version.ref = "firebasePerfPlugin" }hilt-android = { group = "com.google.dagger", name = "hilt-android", version.ref = "hilt" }hilt-android-testing = { group = "com.google.dagger", name = "hilt-android-testing", version.ref = "hilt" }hilt-compiler = { group = "com.google.dagger", name = "hilt-android-compiler", version.ref = "hilt" }@@ -138,9 +139,9 @@ ksp-gradlePlugin = { group = "com.google.devtools.ksp", name = "com.google.devtoandroid-application = { id = "com.android.application", version.ref = "androidGradlePlugin" }android-library = { id = "com.android.library", version.ref = "androidGradlePlugin" }android-test = { id = "com.android.test", version.ref = "androidGradlePlugin" }-firebase-crashlytics = { id = "com.google.firebase.crashlytics", version.ref = "firebaseCrashlyticsPlugin"}-firebase-perf = { id = "com.google.firebase.firebase-perf", version.ref = "firebasePerfPlugin"}-gms = { id = "com.google.gms.google-services", version.ref = "gmsPlugin"}+firebase-crashlytics = { id = "com.google.firebase.crashlytics", version.ref = "firebaseCrashlyticsPlugin" }+firebase-perf = { id = "com.google.firebase.firebase-perf", version.ref = "firebasePerfPlugin" }+gms = { id = "com.google.gms.google-services", version.ref = "gmsPlugin" }hilt = { id = "com.google.dagger.hilt.android", version.ref = "hilt" }kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" }kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }diff --git a/settings.gradle.kts b/settings.gradle.ktsindex 857f9d56c..2af582a7b 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -47,6 +47,7 @@ include(":core:network")include(":core:ui")include(":core:testing")include(":core:analytics")+include(":core:notifications")include(":feature:foryou")include(":feature:interests")diff --git a/sync/sync-test/src/main/java/com/google/samples/apps/nowinandroid/core/sync/test/NeverSyncingSyncStatusMonitor.kt b/sync/sync-test/src/main/java/com/google/samples/apps/nowinandroid/core/sync/test/NeverSyncingSyncManager.ktsimilarity index 82%rename from sync/sync-test/src/main/java/com/google/samples/apps/nowinandroid/core/sync/test/NeverSyncingSyncStatusMonitor.ktrename to sync/sync-test/src/main/java/com/google/samples/apps/nowinandroid/core/sync/test/NeverSyncingSyncManager.ktindex 647dd864e..2b0b4fb6a 100644--- a/sync/sync-test/src/main/java/com/google/samples/apps/nowinandroid/core/sync/test/NeverSyncingSyncStatusMonitor.kt+++ b/sync/sync-test/src/main/java/com/google/samples/apps/nowinandroid/core/sync/test/NeverSyncingSyncManager.kt@@ -16,11 +16,12 @@package com.google.samples.apps.nowinandroid.core.sync.test-import com.google.samples.apps.nowinandroid.core.data.util.SyncStatusMonitor+import com.google.samples.apps.nowinandroid.core.data.util.SyncManagerimport kotlinx.coroutines.flow.Flowimport kotlinx.coroutines.flow.flowOfimport javax.inject.Inject-class NeverSyncingSyncStatusMonitor @Inject constructor() : SyncStatusMonitor {+class NeverSyncingSyncManager @Inject constructor() : SyncManager {override val isSyncing: Flow<Boolean> = flowOf(false)+ override fun requestSync() = Unit}diff --git a/sync/sync-test/src/main/java/com/google/samples/apps/nowinandroid/core/sync/test/TestSyncModule.kt b/sync/sync-test/src/main/java/com/google/samples/apps/nowinandroid/core/sync/test/TestSyncModule.ktindex 323704b5a..0089450b5 100644--- a/sync/sync-test/src/main/java/com/google/samples/apps/nowinandroid/core/sync/test/TestSyncModule.kt+++ b/sync/sync-test/src/main/java/com/google/samples/apps/nowinandroid/core/sync/test/TestSyncModule.kt@@ -16,7 +16,7 @@package com.google.samples.apps.nowinandroid.core.sync.test-import com.google.samples.apps.nowinandroid.core.data.util.SyncStatusMonitor+import com.google.samples.apps.nowinandroid.core.data.util.SyncManagerimport com.google.samples.apps.nowinandroid.sync.di.SyncModuleimport dagger.Bindsimport dagger.Module@@ -31,6 +31,6 @@ import dagger.hilt.testing.TestInstallIninterface TestSyncModule {@Bindsfun bindsSyncStatusMonitor(- syncStatusMonitor: NeverSyncingSyncStatusMonitor,- ): SyncStatusMonitor+ syncStatusMonitor: NeverSyncingSyncManager,+ ): SyncManager}diff --git a/sync/work/build.gradle.kts b/sync/work/build.gradle.ktsindex b5b3bdb68..fa7835323 100644--- a/sync/work/build.gradle.kts+++ b/sync/work/build.gradle.kts@@ -36,6 +36,7 @@ dependencies {implementation(libs.androidx.startup)implementation(libs.androidx.tracing.ktx)implementation(libs.androidx.work.ktx)+ implementation(libs.firebase.cloud.messaging)implementation(libs.hilt.ext.work)implementation(libs.kotlinx.coroutines.android)diff --git a/sync/work/src/demo/AndroidManifest.xml b/sync/work/src/demo/AndroidManifest.xmlnew file mode 100644index 000000000..dac61a5bc--- /dev/null+++ b/sync/work/src/demo/AndroidManifest.xml@@ -0,0 +1,38 @@+<?xml version="1.0" encoding="utf-8"?>+<!--+ Copyright 2022 The Android Open Source Project++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.+-->+<manifest xmlns:android="http://schemas.android.com/apk/res/android"+ xmlns:tools="http://schemas.android.com/tools">++ <application>+ <provider+ android:name="androidx.startup.InitializationProvider"+ android:authorities="${applicationId}.androidx-startup"+ android:exported="false"+ tools:node="merge">+ <!-- TODO: b/2173216 Disable auto sync startup till it works well with instrumented tests -->+ <meta-data+ android:name="com.google.samples.apps.nowinandroid.sync.initializers.SyncInitializer"+ android:value="androidx.startup"+ tools:node="remove" />+ </provider>+ <service+ android:name=".services.SyncNotificationsService"+ android:exported="false"+ tools:node="remove" />+ </application>++</manifest>diff --git a/sync/work/src/main/AndroidManifest.xml b/sync/work/src/main/AndroidManifest.xmlindex 2487eb105..0d0b720bb 100644--- a/sync/work/src/main/AndroidManifest.xml+++ b/sync/work/src/main/AndroidManifest.xml@@ -29,7 +29,13 @@android:value="androidx.startup"tools:node="remove" /></provider>-+ <service+ android:name=".services.SyncNotificationsService"+ android:exported="false">+ <intent-filter>+ <action android:name="com.google.firebase.MESSAGING_EVENT" />+ </intent-filter>+ </service></application></manifest>diff --git a/sync/work/src/main/java/com/google/samples/apps/nowinandroid/sync/di/SyncModule.kt b/sync/work/src/main/java/com/google/samples/apps/nowinandroid/sync/di/SyncModule.ktindex 68f9eee93..bbc45dc42 100644--- a/sync/work/src/main/java/com/google/samples/apps/nowinandroid/sync/di/SyncModule.kt+++ b/sync/work/src/main/java/com/google/samples/apps/nowinandroid/sync/di/SyncModule.kt@@ -16,8 +16,8 @@package com.google.samples.apps.nowinandroid.sync.di-import com.google.samples.apps.nowinandroid.core.data.util.SyncStatusMonitor-import com.google.samples.apps.nowinandroid.sync.status.WorkManagerSyncStatusMonitor+import com.google.samples.apps.nowinandroid.core.data.util.SyncManager+import com.google.samples.apps.nowinandroid.sync.status.WorkManagerSyncManagerimport dagger.Bindsimport dagger.Moduleimport dagger.hilt.InstallIn@@ -28,6 +28,6 @@ import dagger.hilt.components.SingletonComponentinterface SyncModule {@Bindsfun bindsSyncStatusMonitor(- syncStatusMonitor: WorkManagerSyncStatusMonitor,- ): SyncStatusMonitor+ syncStatusMonitor: WorkManagerSyncManager,+ ): SyncManager}diff --git a/sync/work/src/main/java/com/google/samples/apps/nowinandroid/sync/services/SyncNotificationsService.kt b/sync/work/src/main/java/com/google/samples/apps/nowinandroid/sync/services/SyncNotificationsService.ktnew file mode 100644index 000000000..ab318776a--- /dev/null+++ b/sync/work/src/main/java/com/google/samples/apps/nowinandroid/sync/services/SyncNotificationsService.kt@@ -0,0 +1,38 @@+/*+ * Copyright 2023 The Android Open Source Project+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * https://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package com.google.samples.apps.nowinandroid.sync.services++import com.google.firebase.messaging.FirebaseMessagingService+import com.google.firebase.messaging.RemoteMessage+import com.google.samples.apps.nowinandroid.core.data.util.SyncManager+import dagger.hilt.android.AndroidEntryPoint+import javax.inject.Inject++private const val SYNC_TOPIC = "sync"++@AndroidEntryPoint+class SyncNotificationsService : FirebaseMessagingService() {++ @Inject+ lateinit var syncManager: SyncManager++ override fun onMessageReceived(message: RemoteMessage) {+ if (SYNC_TOPIC == message.from) {+ syncManager.requestSync()+ }+ }+}diff --git a/sync/work/src/main/java/com/google/samples/apps/nowinandroid/sync/status/WorkManagerSyncStatusMonitor.kt b/sync/work/src/main/java/com/google/samples/apps/nowinandroid/sync/status/WorkManagerSyncManager.ktsimilarity index 67%rename from sync/work/src/main/java/com/google/samples/apps/nowinandroid/sync/status/WorkManagerSyncStatusMonitor.ktrename to sync/work/src/main/java/com/google/samples/apps/nowinandroid/sync/status/WorkManagerSyncManager.ktindex f4f9d02cb..9bb57ccf0 100644--- a/sync/work/src/main/java/com/google/samples/apps/nowinandroid/sync/status/WorkManagerSyncStatusMonitor.kt+++ b/sync/work/src/main/java/com/google/samples/apps/nowinandroid/sync/status/WorkManagerSyncManager.kt@@ -19,27 +19,39 @@ package com.google.samples.apps.nowinandroid.sync.statusimport android.content.Contextimport androidx.lifecycle.asFlowimport androidx.lifecycle.map+import androidx.work.ExistingWorkPolicyimport androidx.work.WorkInfoimport androidx.work.WorkInfo.Stateimport androidx.work.WorkManager-import com.google.samples.apps.nowinandroid.core.data.util.SyncStatusMonitor+import com.google.samples.apps.nowinandroid.core.data.util.SyncManagerimport com.google.samples.apps.nowinandroid.sync.initializers.SyncWorkName+import com.google.samples.apps.nowinandroid.sync.workers.SyncWorkerimport dagger.hilt.android.qualifiers.ApplicationContextimport kotlinx.coroutines.flow.Flowimport kotlinx.coroutines.flow.conflateimport javax.inject.Inject/**- * [SyncStatusMonitor] backed by [WorkInfo] from [WorkManager]+ * [SyncManager] backed by [WorkInfo] from [WorkManager]*/-class WorkManagerSyncStatusMonitor @Inject constructor(- @ApplicationContext context: Context,-) : SyncStatusMonitor {+class WorkManagerSyncManager @Inject constructor(+ @ApplicationContext private val context: Context,+) : SyncManager {override val isSyncing: Flow<Boolean> =WorkManager.getInstance(context).getWorkInfosForUniqueWorkLiveData(SyncWorkName).map(MutableList<WorkInfo>::anyRunning).asFlow().conflate()++ override fun requestSync() {+ val workManager = WorkManager.getInstance(context)+ // Run sync on app startup and ensure only one sync worker runs at any time+ workManager.enqueueUniqueWork(+ SyncWorkName,+ ExistingWorkPolicy.KEEP,+ SyncWorker.startUpSyncWork(),+ )+ }}private val List<WorkInfo>.anyRunning get() = any { it.state == State.RUNNING }