diff --git a/app/src/androidTest/java/com/android/polybazaar/PolyBazaarTestCase.kt b/app/src/androidTest/java/com/android/polybazaar/PolyBazaarTestCase.kt
index 6f743625..051d505f 100644
--- a/app/src/androidTest/java/com/android/polybazaar/PolyBazaarTestCase.kt
+++ b/app/src/androidTest/java/com/android/polybazaar/PolyBazaarTestCase.kt
@@ -9,6 +9,7 @@ import androidx.test.core.app.ApplicationProvider
import com.android.polybazaar.auth.viewmodel.AuthViewModel
import com.android.polybazaar.booking.model.FakeBookingRepository
import com.android.polybazaar.chat.model.FakeChatRepository
+import com.android.polybazaar.connectivity.model.FakeConnectivityRepository
import com.android.polybazaar.listing.model.FakeListingRepository
import com.android.polybazaar.listing.model.FilePhotoStorage
import com.android.polybazaar.map.model.FakeLocationRepository
@@ -59,6 +60,7 @@ abstract class PolyBazaarTestCase :
chatRepository = FakeChatRepository(),
bookingRepository = FakeBookingRepository(),
locationRepository = FakeLocationRepository(),
+ connectivityRepository = FakeConnectivityRepository(),
navController = rememberNavController(),
)
}
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index d21d9861..fae0ddb6 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -17,6 +17,8 @@
keeps it on the device, in its saved state, so the picker still opens there after the app
is killed. Without it the user picks their campus instead. -->
+
+
+}
+
+/**
+ * A [ConnectivityRepository] that follows Android's default network.
+ *
+ * Its callback is never unregistered: create one per process, with the application context, and
+ * share it, so it lives as long as the app does.
+ */
+class AndroidConnectivityRepository(context: Context) : ConnectivityRepository {
+
+ private val connectivityManager =
+ context.applicationContext.getSystemService(ConnectivityManager::class.java)
+
+ private val _isOnline =
+ MutableStateFlow(
+ reachesInternet(
+ connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
+ )
+ )
+ override val isOnline: StateFlow = _isOnline.asStateFlow()
+
+ /** The default network the callback last reported, or null once it is lost. */
+ @Volatile private var defaultNetwork: Network? = connectivityManager.activeNetwork
+
+ init {
+ connectivityManager.registerDefaultNetworkCallback(
+ object : ConnectivityManager.NetworkCallback() {
+ // Also called right after a new default network becomes available.
+ override fun onCapabilitiesChanged(network: Network, capabilities: NetworkCapabilities) {
+ defaultNetwork = network
+ _isOnline.value = reachesInternet(capabilities)
+ }
+
+ // During a Wi-Fi/mobile handoff the old network can be lost after the new one became
+ // the default: only losing the current default means the device is offline.
+ override fun onLost(network: Network) {
+ if (network != defaultNetwork) return
+ defaultNetwork = null
+ _isOnline.value = false
+ }
+ }
+ )
+ }
+
+ /** Whether [capabilities] reach the internet: validated, so not stuck behind a login page. */
+ private fun reachesInternet(capabilities: NetworkCapabilities?): Boolean =
+ capabilities != null &&
+ capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
+ capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
+}
diff --git a/app/src/main/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModel.kt b/app/src/main/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModel.kt
index a06c8505..c9dd0f52 100644
--- a/app/src/main/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModel.kt
+++ b/app/src/main/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModel.kt
@@ -8,6 +8,7 @@ import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.android.polybazaar.auth.model.AuthRules
import com.android.polybazaar.booking.model.upcomingDays
+import com.android.polybazaar.connectivity.model.ConnectivityRepository
import com.android.polybazaar.error.model.AppError
import com.android.polybazaar.error.model.toAppError
import com.android.polybazaar.listing.model.ItemListing
@@ -66,6 +67,8 @@ import kotlinx.coroutines.launch
* until a Retry succeeds.
* @property savedListing the saved listing, until the screen has handled it.
* @property saveError why the last save failed, or null.
+ * @property isOnline whether the device is online, which choosing a location on the map needs.
+ * Followed live, never saved with the form.
*/
data class ListingFormUiState(
val today: LocalDate,
@@ -90,6 +93,7 @@ data class ListingFormUiState(
val savedListing: Listing? = null,
val isSaving: Boolean = false,
val saveError: AppError? = null,
+ val isOnline: Boolean = true,
) {
/** Whether this form edits a saved listing rather than creating one. */
val isEditing: Boolean
@@ -187,6 +191,8 @@ private fun formFor(listing: Listing, today: LocalDate) =
* camera app is in front. Pass `createSavedStateHandle()` from the factory: a handle made by hand
* is not saved by Android.
* @param locationRepository finds the lender, to open the map picker where they are.
+ * @param connectivityRepository tells whether the device is online, see
+ * [ListingFormUiState.isOnline].
* @param today the current day, to leave past available days out of an edited listing.
*/
class ListingFormViewModel(
@@ -195,10 +201,16 @@ class ListingFormViewModel(
private val photoStorage: PhotoStorage,
private val savedStateHandle: SavedStateHandle,
private val locationRepository: LocationRepository,
+ connectivityRepository: ConnectivityRepository,
private val today: () -> LocalDate = LocalDate::now,
) : ViewModel() {
- private val _uiState = MutableStateFlow(savedStateHandle.restoreForm(listingId, today()))
+ private val _uiState =
+ MutableStateFlow(
+ savedStateHandle
+ .restoreForm(listingId, today())
+ .copy(isOnline = connectivityRepository.isOnline.value)
+ )
val uiState: StateFlow = _uiState.asStateFlow()
/**
@@ -236,6 +248,11 @@ class ListingFormViewModel(
photoStorage.deleteAllExcept(_uiState.value.photos + listOfNotNull(pendingPhoto))
// A restored edit form holds the user's changes, which loading the listing would overwrite.
if (listingId != null && savedStateHandle.get(LOADED) != true) loadListing()
+ viewModelScope.launch {
+ connectivityRepository.isOnline.collect { online ->
+ _uiState.update { it.copy(isOnline = online) }
+ }
+ }
}
/**
@@ -253,7 +270,9 @@ class ListingFormViewModel(
.getListing(id)
.onSuccess { listing ->
savedStateHandle[LOADED] = true
- updateState { formFor(listing, today()).copy(isLoading = true) }
+ updateState {
+ formFor(listing, today()).copy(isLoading = true, isOnline = it.isOnline)
+ }
}
.onFailure { exception ->
// Cancellation means the screen was closed: it is not an error to show.
@@ -447,7 +466,7 @@ class ListingFormViewModel(
val form =
if (state.isEditing) formFor(savedListing, today())
else ListingFormUiState(today = today())
- form.copy(savedListing = savedListing)
+ form.copy(savedListing = savedListing, isOnline = it.isOnline)
}
} catch (exception: Exception) {
if (exception is CancellationException) {
diff --git a/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt b/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt
index 75d0b661..042ff23e 100644
--- a/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt
+++ b/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt
@@ -72,6 +72,7 @@ import com.android.polybazaar.chat.ui.InboxScreen
import com.android.polybazaar.chat.viewmodel.ConversationViewModel
import com.android.polybazaar.chat.viewmodel.InboxViewModel
import com.android.polybazaar.chat.viewmodel.photoUploadScope
+import com.android.polybazaar.connectivity.model.ConnectivityRepository
import com.android.polybazaar.error.model.AppError
import com.android.polybazaar.error.ui.message
import com.android.polybazaar.listing.model.FilePhotoStorage
@@ -121,6 +122,7 @@ object AppNavHostTags {
* @param editPhotoStorage keeps the photos added to the listing being edited. It must use another
* folder than [photoStorage]: opening a form deletes the photos its folder holds for other forms.
* @param locationRepository finds the lender, to open the listing form's map picker where they are.
+ * @param connectivityRepository tells the listing forms whether the device is online.
*/
@Composable
fun AppNavHost(
@@ -133,6 +135,7 @@ fun AppNavHost(
chatRepository: ChatRepository,
bookingRepository: BookingRepository,
locationRepository: LocationRepository,
+ connectivityRepository: ConnectivityRepository,
navController: NavHostController = rememberNavController(),
) {
val uiState by authViewModel.uiState.collectAsState()
@@ -304,6 +307,7 @@ fun AppNavHost(
photoStorage = photoStorage,
savedStateHandle = createSavedStateHandle(),
locationRepository = locationRepository,
+ connectivityRepository = connectivityRepository,
)
}
}
@@ -331,6 +335,7 @@ fun AppNavHost(
photoStorage = editPhotoStorage,
savedStateHandle = createSavedStateHandle(),
locationRepository = locationRepository,
+ connectivityRepository = connectivityRepository,
)
}
}
diff --git a/app/src/sharedTest/java/com/android/polybazaar/connectivity/model/FakeConnectivityRepository.kt b/app/src/sharedTest/java/com/android/polybazaar/connectivity/model/FakeConnectivityRepository.kt
new file mode 100644
index 00000000..5cdcef7b
--- /dev/null
+++ b/app/src/sharedTest/java/com/android/polybazaar/connectivity/model/FakeConnectivityRepository.kt
@@ -0,0 +1,9 @@
+// Co-authored-by: Claude Code (Claude Opus 5.5)
+package com.android.polybazaar.connectivity.model
+
+import kotlinx.coroutines.flow.MutableStateFlow
+
+/** A [ConnectivityRepository] for tests: set [isOnline] to go offline or back online. */
+class FakeConnectivityRepository(online: Boolean = true) : ConnectivityRepository {
+ override val isOnline = MutableStateFlow(online)
+}
diff --git a/app/src/test/java/com/android/polybazaar/connectivity/model/AndroidConnectivityRepositoryTest.kt b/app/src/test/java/com/android/polybazaar/connectivity/model/AndroidConnectivityRepositoryTest.kt
new file mode 100644
index 00000000..d8529454
--- /dev/null
+++ b/app/src/test/java/com/android/polybazaar/connectivity/model/AndroidConnectivityRepositoryTest.kt
@@ -0,0 +1,80 @@
+// Co-authored-by: Claude Code (Claude Opus 5.5)
+package com.android.polybazaar.connectivity.model
+
+import android.content.Context
+import android.net.ConnectivityManager
+import android.net.NetworkCapabilities
+import androidx.test.core.app.ApplicationProvider
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.Shadows.shadowOf
+import org.robolectric.shadows.ShadowNetwork
+import org.robolectric.shadows.ShadowNetworkCapabilities
+
+/** [AndroidConnectivityRepository] on Robolectric's [ConnectivityManager]. */
+@RunWith(AndroidJUnit4::class)
+class AndroidConnectivityRepositoryTest {
+
+ private val context: Context = ApplicationProvider.getApplicationContext()
+ private val connectivityManager = context.getSystemService(ConnectivityManager::class.java)
+
+ private fun capabilities(vararg capabilities: Int): NetworkCapabilities =
+ ShadowNetworkCapabilities.newInstance().also { network ->
+ capabilities.forEach { shadowOf(network).addCapability(it) }
+ }
+
+ private val validated =
+ capabilities(
+ NetworkCapabilities.NET_CAPABILITY_INTERNET,
+ NetworkCapabilities.NET_CAPABILITY_VALIDATED,
+ )
+
+ /** Gives the active network [capabilities], then creates the repository. */
+ private fun repositoryOn(capabilities: NetworkCapabilities?): AndroidConnectivityRepository {
+ shadowOf(connectivityManager)
+ .setNetworkCapabilities(connectivityManager.activeNetwork, capabilities)
+ return AndroidConnectivityRepository(context)
+ }
+
+ @Test
+ fun startsOffline_withoutAValidatedInternetNetwork() {
+ // Behind a login page, the network has the internet capability but is not validated.
+ assertFalse(
+ repositoryOn(capabilities(NetworkCapabilities.NET_CAPABILITY_INTERNET)).isOnline.value
+ )
+ assertFalse(repositoryOn(null).isOnline.value)
+ }
+
+ @Test
+ fun followsTheDefaultNetwork() {
+ val repository = repositoryOn(validated)
+ val callback = shadowOf(connectivityManager).networkCallbacks.single()
+ val network = connectivityManager.activeNetwork!!
+ assertTrue(repository.isOnline.value)
+
+ callback.onLost(network)
+ assertFalse(repository.isOnline.value)
+
+ callback.onCapabilitiesChanged(network, validated)
+ assertTrue(repository.isOnline.value)
+ }
+
+ @Test
+ fun staysOnline_whenThePreviousNetworkIsLostAfterAHandoff() {
+ val repository = repositoryOn(validated)
+ val callback = shadowOf(connectivityManager).networkCallbacks.single()
+ val wifi = connectivityManager.activeNetwork!!
+ val mobile = ShadowNetwork.newInstance(shadowOf(wifi).netId + 1)
+
+ // Mobile becomes the default, validated, before Wi-Fi's loss arrives.
+ callback.onCapabilitiesChanged(mobile, validated)
+ callback.onLost(wifi)
+ assertTrue(repository.isOnline.value)
+
+ callback.onLost(mobile)
+ assertFalse(repository.isOnline.value)
+ }
+}
diff --git a/app/src/test/java/com/android/polybazaar/listing/ui/CreateListingScreenTest.kt b/app/src/test/java/com/android/polybazaar/listing/ui/CreateListingScreenTest.kt
index 1943ad24..aa88c48e 100644
--- a/app/src/test/java/com/android/polybazaar/listing/ui/CreateListingScreenTest.kt
+++ b/app/src/test/java/com/android/polybazaar/listing/ui/CreateListingScreenTest.kt
@@ -45,6 +45,7 @@ import androidx.test.ext.junit.runners.AndroidJUnit4
import com.android.polybazaar.R
import com.android.polybazaar.booking.ui.AvailabilityCalendarSheetTags
import com.android.polybazaar.booking.ui.AvailabilityCalendarTags
+import com.android.polybazaar.connectivity.model.FakeConnectivityRepository
import com.android.polybazaar.listing.model.FilePhotoStorage
import com.android.polybazaar.listing.model.ItemListing
import com.android.polybazaar.listing.model.Listing
@@ -99,6 +100,7 @@ class CreateListingScreenTest {
createStorage(),
SavedStateHandle(),
FakeLocationRepository(),
+ FakeConnectivityRepository(),
today,
)
setContentWithRegistry(registry) {
@@ -887,6 +889,7 @@ class CreateListingScreenTest {
createStorage(),
SavedStateHandle(),
FakeLocationRepository(),
+ FakeConnectivityRepository(),
)
var createdCount = 0
val owner =
diff --git a/app/src/test/java/com/android/polybazaar/listing/ui/EditListingScreenTest.kt b/app/src/test/java/com/android/polybazaar/listing/ui/EditListingScreenTest.kt
index 69638d6c..464500b8 100644
--- a/app/src/test/java/com/android/polybazaar/listing/ui/EditListingScreenTest.kt
+++ b/app/src/test/java/com/android/polybazaar/listing/ui/EditListingScreenTest.kt
@@ -27,6 +27,7 @@ import androidx.test.ext.junit.runners.AndroidJUnit4
import com.android.polybazaar.R
import com.android.polybazaar.booking.model.formatRuns
import com.android.polybazaar.booking.model.groupIntoRuns
+import com.android.polybazaar.connectivity.model.FakeConnectivityRepository
import com.android.polybazaar.listing.model.FakeListingRepository
import com.android.polybazaar.listing.model.FilePhotoStorage
import com.android.polybazaar.listing.model.ItemListing
@@ -99,6 +100,7 @@ class EditListingScreenTest {
FilePhotoStorage(context, FilePhotoStorage.EDIT_FORM),
SavedStateHandle(),
FakeLocationRepository(),
+ FakeConnectivityRepository(),
)
composeTestRule.setContent {
EditListingScreen(
@@ -343,6 +345,7 @@ class EditListingScreenTest {
FilePhotoStorage(context, FilePhotoStorage.EDIT_FORM),
SavedStateHandle(),
FakeLocationRepository(),
+ FakeConnectivityRepository(),
)
composeTestRule.setContent {
dispatcher = LocalOnBackPressedDispatcherOwner.current!!.onBackPressedDispatcher
diff --git a/app/src/test/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModelTest.kt b/app/src/test/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModelTest.kt
index aee84add..33d16b9b 100644
--- a/app/src/test/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModelTest.kt
+++ b/app/src/test/java/com/android/polybazaar/listing/viewmodel/ListingFormViewModelTest.kt
@@ -7,6 +7,7 @@ import android.os.Parcel
import androidx.core.os.bundleOf
import androidx.lifecycle.SavedStateHandle
import androidx.test.ext.junit.runners.AndroidJUnit4
+import com.android.polybazaar.connectivity.model.FakeConnectivityRepository
import com.android.polybazaar.error.model.AppError
import com.android.polybazaar.listing.model.ItemListing
import com.android.polybazaar.listing.model.Listing
@@ -57,6 +58,7 @@ class ListingFormViewModelTest {
private lateinit var photoStorage: FakePhotoStorage
private lateinit var savedStateHandle: SavedStateHandle
private val locationRepository = FakeLocationRepository()
+ private val connectivity = FakeConnectivityRepository()
private lateinit var viewModel: ListingFormViewModel
private val listing =
@@ -73,11 +75,24 @@ class ListingFormViewModelTest {
repository = FakeListingRepository()
photoStorage = FakePhotoStorage()
savedStateHandle = SavedStateHandle()
- viewModel =
- ListingFormViewModel(null, repository, photoStorage, savedStateHandle, locationRepository) {
- today
- }
- }
+ viewModel = newForm(null) { today }
+ }
+
+ /** A form on this test's fakes, editing [listingId] or creating a listing when it is null. */
+ private fun newForm(
+ listingId: String?,
+ handle: SavedStateHandle = savedStateHandle,
+ today: () -> LocalDate = LocalDate::now,
+ ) =
+ ListingFormViewModel(
+ listingId,
+ repository,
+ photoStorage,
+ handle,
+ locationRepository,
+ connectivity,
+ today,
+ )
@After
fun tearDown() {
@@ -293,14 +308,7 @@ class ListingFormViewModelTest {
viewModel.addPhotos(uris(1))
viewModel.startTakingPhoto(retakeIndex = null)
- val restored =
- ListingFormViewModel(
- null,
- repository,
- photoStorage,
- afterAppKilled(savedStateHandle),
- locationRepository,
- )
+ val restored = newForm(null, afterAppKilled(savedStateHandle))
restored.finishTakingPhoto(saved = true)
assertEquals(
@@ -316,7 +324,7 @@ class ListingFormViewModelTest {
viewModel.addPhotos(uris(1))
viewModel.startTakingPhoto(retakeIndex = null)
- ListingFormViewModel(null, repository, photoStorage, savedStateHandle, locationRepository)
+ newForm(null)
assertEquals(uris(1) + photoStorage.taken[0].uri, photoStorage.keptOnCleanup.last())
}
@@ -498,14 +506,7 @@ class ListingFormViewModelTest {
testDispatcher.scheduler.advanceUntilIdle()
assertEquals(AppError.NETWORK, viewModel.uiState.value.saveError)
- val restored =
- ListingFormViewModel(
- null,
- repository,
- photoStorage,
- afterAppKilled(savedStateHandle),
- locationRepository,
- )
+ val restored = newForm(null, afterAppKilled(savedStateHandle))
// The form comes back, the error of a save that no longer runs does not.
assertEquals("Math tutoring", restored.uiState.value.title)
@@ -641,8 +642,7 @@ class ListingFormViewModelTest {
repository.storedListing = storedItem
// The same fixed day as the other forms: with the real date, available days chosen in these
// tests end up in the past and are dropped.
- val editViewModel =
- ListingFormViewModel("l1", repository, photoStorage, handle, locationRepository) { today }
+ val editViewModel = newForm("l1", handle) { today }
testDispatcher.scheduler.advanceUntilIdle()
return editViewModel
}
@@ -661,8 +661,7 @@ class ListingFormViewModelTest {
fun edit_showsLoadingUntilTheListingArrives() = runTest {
repository.storedListing = storedItem
repository.pendingLoad = CompletableDeferred()
- val editViewModel =
- ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository)
+ val editViewModel = newForm("l1")
testDispatcher.scheduler.runCurrent()
assertTrue(editViewModel.uiState.value.isLoading)
@@ -680,8 +679,7 @@ class ListingFormViewModelTest {
fun edit_formCannotBeChangedWhileLoading() = runTest {
repository.storedListing = storedItem
repository.pendingLoad = CompletableDeferred()
- val editViewModel =
- ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository)
+ val editViewModel = newForm("l1")
testDispatcher.scheduler.runCurrent()
assertFalse(editViewModel.uiState.value.canEdit)
@@ -708,8 +706,7 @@ class ListingFormViewModelTest {
fun edit_formCannotBeChangedAfterALoadFailure() = runTest {
repository.storedListing = storedItem
repository.loadFailure = UnknownHostException("offline")
- val editViewModel =
- ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository)
+ val editViewModel = newForm("l1")
testDispatcher.scheduler.advanceUntilIdle()
assertFalse(editViewModel.uiState.value.canEdit)
@@ -733,8 +730,7 @@ class ListingFormViewModelTest {
savedStateHandle["pendingPhoto"] = photo
repository.storedListing = storedItem
repository.pendingLoad = CompletableDeferred()
- val editViewModel =
- ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository)
+ val editViewModel = newForm("l1")
testDispatcher.scheduler.runCurrent()
editViewModel.finishTakingPhoto(saved = true)
@@ -763,8 +759,7 @@ class ListingFormViewModelTest {
repository.storedListing = storedItem
repository.loadFailure =
FirebaseFirestoreException("missing", FirebaseFirestoreException.Code.NOT_FOUND)
- val editViewModel =
- ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository)
+ val editViewModel = newForm("l1")
testDispatcher.scheduler.advanceUntilIdle()
assertEquals(AppError.NOT_FOUND, editViewModel.uiState.value.loadError)
@@ -901,8 +896,7 @@ class ListingFormViewModelTest {
fun edit_loadFailureSetsLoadErrorNotSaveError() = runTest {
repository.storedListing = storedItem
repository.loadFailure = UnknownHostException("offline")
- val editViewModel =
- ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository)
+ val editViewModel = newForm("l1")
testDispatcher.scheduler.advanceUntilIdle()
assertEquals(AppError.NETWORK, editViewModel.uiState.value.loadError)
@@ -914,8 +908,7 @@ class ListingFormViewModelTest {
fun edit_listingAboveThePhotoLimitAcceptsNoNewPhotos() = runTest {
val paths = (0..MAX_PHOTOS).map { "listings/u/l1/old/$it" }
repository.storedListing = storedItem.copy(imagePaths = paths)
- val editViewModel =
- ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository)
+ val editViewModel = newForm("l1")
testDispatcher.scheduler.advanceUntilIdle()
editViewModel.addPhotos(uris(1))
@@ -930,8 +923,7 @@ class ListingFormViewModelTest {
fun edit_cancelledLoadShowsNoErrorAndCanBeRetried() = runTest {
repository.storedListing = storedItem
repository.loadFailure = CancellationException()
- val editViewModel =
- ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository)
+ val editViewModel = newForm("l1")
testDispatcher.scheduler.advanceUntilIdle()
// Cancellation means the screen closed, so it is not an error, and the load is not stuck.
@@ -949,8 +941,7 @@ class ListingFormViewModelTest {
fun edit_loadIsIgnoredWhileOneIsRunning() = runTest {
repository.storedListing = storedItem
repository.pendingLoad = CompletableDeferred()
- val editViewModel =
- ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository)
+ val editViewModel = newForm("l1")
testDispatcher.scheduler.runCurrent()
editViewModel.loadListing()
@@ -965,8 +956,7 @@ class ListingFormViewModelTest {
fun edit_serviceListingLoadsWithoutARefundValue() = runTest {
val service = listing.copy(imagePaths = storedPaths, listingId = "l1", ownerUid = "owner")
repository.storedListing = service
- val editViewModel =
- ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository)
+ val editViewModel = newForm("l1")
testDispatcher.scheduler.advanceUntilIdle()
assertEquals("", editViewModel.uiState.value.refundValue)
@@ -1134,16 +1124,7 @@ class ListingFormViewModelTest {
fun availableDates_surviveTheAppBeingKilled() = runTest {
viewModel.updateAvailableDates(chosenDays)
- val restored =
- ListingFormViewModel(
- null,
- repository,
- photoStorage,
- afterAppKilled(savedStateHandle),
- locationRepository,
- ) {
- today
- }
+ val restored = newForm(null, afterAppKilled(savedStateHandle)) { today }
assertEquals(chosenDays, restored.uiState.value.availableDates)
}
@@ -1151,16 +1132,7 @@ class ListingFormViewModelTest {
@Test
fun save_afterTheDayChanged_leavesOutTheDaysNowPast() = runTest {
var now = today
- val form =
- ListingFormViewModel(
- null,
- repository,
- photoStorage,
- SavedStateHandle(),
- locationRepository,
- ) {
- now
- }
+ val form = newForm(null, SavedStateHandle()) { now }
viewModel = form
fillForm()
form.updateAvailableDates(chosenDays)
@@ -1177,16 +1149,7 @@ class ListingFormViewModelTest {
viewModel.updateAvailableDates(chosenDays)
val laterDay = LocalDate.of(2026, 11, 20)
- val restored =
- ListingFormViewModel(
- null,
- repository,
- photoStorage,
- afterAppKilled(savedStateHandle),
- locationRepository,
- ) {
- laterDay
- }
+ val restored = newForm(null, afterAppKilled(savedStateHandle)) { laterDay }
assertEquals(setOf(LocalDate.of(2026, 11, 28)), restored.uiState.value.availableDates)
assertEquals(laterDay, restored.uiState.value.today)
@@ -1196,10 +1159,7 @@ class ListingFormViewModelTest {
fun edit_showsTheStoredAvailableDays_withoutThePastOnes() = runTest {
repository.storedListing =
storedItem.copy(availableDates = chosenDays + LocalDate.of(2026, 11, 9) + today)
- val editViewModel =
- ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) {
- today
- }
+ val editViewModel = newForm("l1") { today }
testDispatcher.scheduler.advanceUntilIdle()
assertEquals(chosenDays + today, editViewModel.uiState.value.availableDates)
@@ -1233,10 +1193,7 @@ class ListingFormViewModelTest {
@Test
fun edit_loadsTheStoredLocationIntoTheForm() = runTest {
repository.storedListing = storedItem.copy(location = storedLocation)
- val editViewModel =
- ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) {
- today
- }
+ val editViewModel = newForm("l1") { today }
testDispatcher.scheduler.advanceUntilIdle()
assertEquals(storedLocation, editViewModel.uiState.value.location)
@@ -1247,10 +1204,7 @@ class ListingFormViewModelTest {
@Test
fun edit_saveKeepsTheStoredLocation() = runTest {
repository.storedListing = storedItem.copy(location = storedLocation)
- val editViewModel =
- ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) {
- today
- }
+ val editViewModel = newForm("l1") { today }
testDispatcher.scheduler.advanceUntilIdle()
repository.result = storedItem.copy(price = 15.0, location = storedLocation)
@@ -1275,9 +1229,7 @@ class ListingFormViewModelTest {
@Test
fun location_survivesTheAppBeingKilled() = runTest {
repository.storedListing = storedItem.copy(location = storedLocation)
- ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) {
- today
- }
+ newForm("l1") { today }
testDispatcher.scheduler.advanceUntilIdle()
assertEquals(storedLocation.latitude, savedStateHandle.get("locationLatitude"))
@@ -1309,8 +1261,7 @@ class ListingFormViewModelTest {
)
handles.forEach { handle ->
- val restored =
- ListingFormViewModel(null, repository, photoStorage, handle, locationRepository) { today }
+ val restored = newForm(null, handle) { today }
assertNull(restored.uiState.value.location)
}
}
@@ -1453,8 +1404,7 @@ class ListingFormViewModelTest {
locationRepository.location = lausanne
repository.storedListing = storedItem.copy(location = storedLocation)
repository.pendingLoad = CompletableDeferred()
- val editViewModel =
- ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository)
+ val editViewModel = newForm("l1")
testDispatcher.scheduler.runCurrent()
editViewModel.locateLender()
@@ -1523,8 +1473,7 @@ class ListingFormViewModelTest {
fun locationChanges_areIgnoredWhileTheEditedListingLoads() = runTest {
repository.storedListing = storedItem.copy(location = storedLocation)
repository.pendingLoad = CompletableDeferred()
- val editViewModel =
- ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository)
+ val editViewModel = newForm("l1")
testDispatcher.scheduler.runCurrent()
editViewModel.setLocationPoint(lausanne)
@@ -1541,8 +1490,7 @@ class ListingFormViewModelTest {
@Test
fun edit_opensThePickerOnTheStoredLocation_orEpflWithoutOne() = runTest {
repository.storedListing = storedItem.copy(location = ListingLocation(46.5, 6.6, "Flat"))
- val withLocation =
- ListingFormViewModel("l1", repository, photoStorage, SavedStateHandle(), locationRepository)
+ val withLocation = newForm("l1", SavedStateHandle())
testDispatcher.scheduler.advanceUntilIdle()
assertEquals(Coordinates(46.5, 6.6), withLocation.uiState.value.suggestedPoint)
@@ -1552,10 +1500,7 @@ class ListingFormViewModelTest {
@Test
fun edit_savesTheChangedLocation() = runTest {
repository.storedListing = storedItem.copy(location = storedLocation)
- val editViewModel =
- ListingFormViewModel("l1", repository, photoStorage, savedStateHandle, locationRepository) {
- today
- }
+ val editViewModel = newForm("l1") { today }
testDispatcher.scheduler.advanceUntilIdle()
repository.result = storedItem
@@ -1568,18 +1513,7 @@ class ListingFormViewModelTest {
@Test
fun suggestedPointAndUnnamedLocation_surviveTheAppBeingKilled() = runTest {
- fun restored() =
- ListingFormViewModel(
- null,
- repository,
- photoStorage,
- afterAppKilled(savedStateHandle),
- locationRepository,
- ) {
- today
- }
- .uiState
- .value
+ fun restored() = newForm(null, afterAppKilled(savedStateHandle)) { today }.uiState.value
locationRepository.location = lausanne
viewModel.locateLender()
testDispatcher.scheduler.advanceUntilIdle()
@@ -1600,9 +1534,50 @@ class ListingFormViewModelTest {
fun suggestedPoint_partlySavedIsRestoredAsEpfl() {
listOf("suggestedLatitude", "suggestedLongitude").forEach { key ->
val handle = SavedStateHandle(mapOf(key to 46.5))
- val restored =
- ListingFormViewModel(null, repository, photoStorage, handle, locationRepository) { today }
+ val restored = newForm(null, handle) { today }
assertEquals(epfl, restored.uiState.value.suggestedPoint)
}
}
+
+ @Test
+ fun isOnline_followsTheConnectivityRepository() = runTest {
+ connectivity.isOnline.value = false
+ val form = newForm(null, SavedStateHandle())
+ assertFalse(form.uiState.value.isOnline)
+
+ connectivity.isOnline.value = true
+ testDispatcher.scheduler.advanceUntilIdle()
+ assertTrue(form.uiState.value.isOnline)
+ }
+
+ @Test
+ fun isOnline_isKeptWhenTheEditedListingLoads() = runTest {
+ repository.storedListing = storedItem
+ repository.pendingLoad = CompletableDeferred()
+ val form = newForm("l1")
+ testDispatcher.scheduler.advanceUntilIdle()
+ connectivity.isOnline.value = false
+ testDispatcher.scheduler.advanceUntilIdle()
+
+ repository.pendingLoad!!.complete(Unit)
+ testDispatcher.scheduler.advanceUntilIdle()
+
+ assertEquals(storedItem.title, form.uiState.value.title)
+ assertFalse(form.uiState.value.isOnline)
+ }
+
+ @Test
+ fun isOnline_isKeptWhenTheFormResetsAfterSaving() = runTest {
+ repository.result = listing
+ testDispatcher.scheduler.advanceUntilIdle()
+ connectivity.isOnline.value = false
+ testDispatcher.scheduler.advanceUntilIdle()
+ fillForm()
+
+ viewModel.save()
+ testDispatcher.scheduler.advanceUntilIdle()
+
+ assertEquals(listing, viewModel.uiState.value.savedListing)
+ assertFalse(viewModel.uiState.value.isOnline)
+ }
}
diff --git a/app/src/test/java/com/android/polybazaar/ui/navigation/AppNavHostTest.kt b/app/src/test/java/com/android/polybazaar/ui/navigation/AppNavHostTest.kt
index 9dbad01c..e7d0a579 100644
--- a/app/src/test/java/com/android/polybazaar/ui/navigation/AppNavHostTest.kt
+++ b/app/src/test/java/com/android/polybazaar/ui/navigation/AppNavHostTest.kt
@@ -73,6 +73,7 @@ import com.android.polybazaar.chat.model.Conversation
import com.android.polybazaar.chat.model.FakeChatRepository
import com.android.polybazaar.chat.ui.ConversationScreenTags
import com.android.polybazaar.chat.ui.InboxScreenTags
+import com.android.polybazaar.connectivity.model.FakeConnectivityRepository
import com.android.polybazaar.error.model.AppError
import com.android.polybazaar.error.model.AppException
import com.android.polybazaar.listing.model.FakeListingRepository
@@ -166,6 +167,7 @@ class AppNavHostTest {
chatRepository = chatRepository,
bookingRepository = bookingRepository,
locationRepository = FakeLocationRepository(),
+ connectivityRepository = FakeConnectivityRepository(),
navController = navController,
)
}
@@ -209,6 +211,7 @@ class AppNavHostTest {
chatRepository = chatRepository,
bookingRepository = bookingRepository,
locationRepository = FakeLocationRepository(),
+ connectivityRepository = FakeConnectivityRepository(),
navController = navController,
)
}
@@ -679,6 +682,7 @@ class AppNavHostTest {
chatRepository = chatRepository,
bookingRepository = bookingRepository,
locationRepository = FakeLocationRepository(),
+ connectivityRepository = FakeConnectivityRepository(),
navController = navController,
)
}
@@ -1511,6 +1515,7 @@ class AppNavHostTest {
chatRepository = chatRepository,
bookingRepository = bookingRepository,
locationRepository = FakeLocationRepository(),
+ connectivityRepository = FakeConnectivityRepository(),
navController = navController,
)
}
@@ -1588,6 +1593,7 @@ class AppNavHostTest {
chatRepository = chatRepository,
bookingRepository = bookingRepository,
locationRepository = FakeLocationRepository(),
+ connectivityRepository = FakeConnectivityRepository(),
navController = navController,
)
}
diff --git a/app/src/test/java/com/android/polybazaar/ui/navigation/EndToEndFlowTest.kt b/app/src/test/java/com/android/polybazaar/ui/navigation/EndToEndFlowTest.kt
index a15cc5b6..e66ca495 100644
--- a/app/src/test/java/com/android/polybazaar/ui/navigation/EndToEndFlowTest.kt
+++ b/app/src/test/java/com/android/polybazaar/ui/navigation/EndToEndFlowTest.kt
@@ -31,6 +31,7 @@ import com.android.polybazaar.auth.viewmodel.AuthViewModel
import com.android.polybazaar.booking.model.FakeBookingRepository
import com.android.polybazaar.browse.ui.BrowseScreenTags
import com.android.polybazaar.chat.model.FakeChatRepository
+import com.android.polybazaar.connectivity.model.FakeConnectivityRepository
import com.android.polybazaar.listing.model.FakeListingRepository
import com.android.polybazaar.listing.model.FilePhotoStorage
import com.android.polybazaar.listing.model.ItemListing
@@ -88,6 +89,7 @@ class EndToEndFlowTest {
chatRepository = FakeChatRepository(),
bookingRepository = FakeBookingRepository(),
locationRepository = FakeLocationRepository(),
+ connectivityRepository = FakeConnectivityRepository(),
navController = navController,
)
}