getCurrentState

abstract fun getCurrentState(): Flow<NetworkState>

Observes the current network connectivity state.

This function returns a cold Flow that emits NetworkState changes in real-time. The flow registers a ConnectivityManager.NetworkCallback when collected and unregisters it when the collector is cancelled, ensuring proper resource cleanup.

Emitted States

Lifecycle

  • The callback is registered when the flow is collected

  • The callback is automatically unregistered when the flow collector is cancelled

  • Each collection creates a new callback registration (cold flow)

Threading

Network callbacks execute on a background thread managed by the system. The flow emissions are thread-safe and can be collected from any coroutine context.

Best Practices

  • Convert to StateFlow in ViewModels for UI consumption

  • Use Flow.distinctUntilChanged to avoid redundant state updates

  • Handle all network states, not just CONNECTED/LOST

Return

A cold Flow that emits NetworkState changes. The flow never completes unless the collector is cancelled.

See also