withFakeReachability

@ObjCName(swiftName = "withFakeReachability")
suspend fun <R> withFakeReachability(initial: ReachabilityStatus = ReachabilityStatus.Unknown, block: suspend (FakeReachability) -> R): R

Install a fresh FakeReachability as Reachability.shared for the duration of block; restore the previous override (or null) on exit; close the fake so the supervisor scope is cancelled. Exception-safe: every step in the finally runs even when block throws.

Nested calls are LIFO-safe by construction — each install captures the previous override in its handle, so the inner uninstall restores the outer fake, and the outer uninstall restores whatever was before that (typically null, meaning the production singleton).

Use from a test (non-suspending or suspending)

// Non-suspending — wrap in runTest to enter a coroutine context.
@Test
fun deviceIsOnline() = runTest {
withFakeReachability(
initial = ReachabilityStatus(
isReachable = true,
transport = Transport.Wifi,
isDataMetered = false,
),
) { fake ->
val vm = MyViewModel() // reads Reachability.shared
assertTrue(vm.online)

fake.setReachable(false)
assertFalse(vm.online)
}
}

// Suspending — runTest handles virtual time and suspend assertions.
@Test
fun reachableFlowReactsToFakeEmissions() = runTest {
withFakeReachability { fake ->
fake.emit(
ReachabilityStatus(
isReachable = true,
transport = Transport.Wifi,
isDataMetered = false,
),
)
Reachability.shared.reachable.test {
assertEquals(true, awaitItem())
}
}
}

Return

the value returned from block.

Parameters

initial

seed ReachabilityStatus; defaults to ReachabilityStatus.Unknown to match the production StateFlow seed.

block

receives the installed fake; drive state with FakeReachability.emit or the convenience setters.