{"id":25560021,"url":"https://github.com/styropyr0/networkwatchdog","last_synced_at":"2026-03-03T00:30:18.861Z","repository":{"id":266517796,"uuid":"898426050","full_name":"styropyr0/NetworkWatchdog","owner":"styropyr0","description":null,"archived":false,"fork":false,"pushed_at":"2024-12-04T17:19:05.000Z","size":130,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2024-12-04T17:41:15.270Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Kotlin","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/styropyr0.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-12-04T11:23:31.000Z","updated_at":"2024-12-04T17:09:46.000Z","dependencies_parsed_at":"2024-12-04T17:41:18.707Z","dependency_job_id":"5620eca5-36fb-43d7-a4a5-226827ccffc7","html_url":"https://github.com/styropyr0/NetworkWatchdog","commit_stats":null,"previous_names":["styropyr0/networkwatchdog"],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/styropyr0%2FNetworkWatchdog","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/styropyr0%2FNetworkWatchdog/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/styropyr0%2FNetworkWatchdog/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/styropyr0%2FNetworkWatchdog/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/styropyr0","download_url":"https://codeload.github.com/styropyr0/NetworkWatchdog/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":239881734,"owners_count":19712632,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-02-20T17:28:53.383Z","updated_at":"2026-03-03T00:30:18.701Z","avatar_url":"https://github.com/styropyr0.png","language":"Kotlin","funding_links":[],"categories":[],"sub_categories":[],"readme":"# **Network Watchdog Library**\n\n**Latest version: 1.0.0**\n\n**Network Watchdog** is a modern, lifecycle-aware library for monitoring network connectivity and internet availability in Android applications. It is designed using **Kotlin Coroutines**, **Jetpack ViewModel**, and **Kotlin Flow**, providing an efficient, thread-safe solution for network state management. The library integrates seamlessly into your app’s architecture, offering both **callback-based** and **observer-based** methods for monitoring network status.\n\n---\n\n## **Why Use Network Watchdog?**\n\n### **Key Features**:\n\n1. **Lifecycle-Aware Design**:  \n   The library starts and stops network monitoring based on the lifecycle of your activities or fragments, ensuring minimal resource usage and avoiding memory leaks. It uses **ViewModel** to ensure network monitoring persists across configuration changes.\n\n2. **Thread-Safe Updates**:  \n   Network state changes are processed off the main thread using **Kotlin Flows**, keeping the main thread responsive. UI updates are safely handled using `runOnUiThread`.\n\n3. **Comprehensive Internet Validation**:  \n   Beyond basic connectivity checks, the library validates active internet access through **NetworkCapabilities**, ensuring that your app only treats the device as “connected” when it has actual internet access.\n\n4. **State Management with ViewModel**:  \n   Network states (`Connected`, `Disconnected`, `NoInternetAccess`, etc.) are exposed via a **StateFlow**, making it easy and efficient to observe network state changes directly from the UI layer.\n\n5. **Optimized Resource Usage**:  \n   The library caches the latest network state using `stateIn`, reducing redundant emissions and improving memory management. This ensures that your app doesn't perform unnecessary work when the network state hasn't changed.\n\n6. **Dual Network Monitoring**:  \n   **Callback-based** and **Observer-based** monitoring: The library supports both methods, so you can choose the most suitable one for your project. Callbacks provide direct actions for different network events, while `StateFlow` provides a declarative, lifecycle-aware method to monitor network changes.\n\n7. **Modern Android Practices**:  \n   The library adheres to Kotlin, Coroutines, and Jetpack components for a clean, maintainable, and scalable architecture.\n\n### **Advantages Over Other Alternatives**:\n\nWhile other solutions may be easier to implement, they often lack lifecycle awareness, don’t handle network state changes efficiently, or result in memory/resource leaks. **Network Watchdog** adheres to Android best practices, making it more robust and scalable.\n\n---\n\n## **Installation**\n\nAdd the following to your `build.gradle` (app-level):\n\n### Gradle (App Level)\n\n```gradle\ndependencies {\n    implementation 'com.github.styropyr0:NetworkWatchdog:v1.0.0'\n}\n```\nor for `app:build.gradle.kts`\n\n```kotlin\ndependencies {\n    implementation(\"com.github.styropyr0:NetworkWatchdog:v1.0.0\")\n}\n```\n\n### Project-level `settings.gradle`\n\n```gradle\ndependencyResolutionManagement {\n    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)\n    repositories {\n        mavenCentral()\n        maven { url 'https://jitpack.io' }\n    }\n}\n```\nor for `settings.gradle.kts`\n\n```kotlin\ndependencyResolutionManagement {\n\t\trepositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)\n\t\trepositories {\n\t\t\tmavenCentral()\n\t\t\tmaven { url = uri(\"https://jitpack.io\") }\n\t\t}\n\t}\n```\n\n---\n\n## **Getting Started**\n\n### **Step 1: Initialize NetworkWatchdog**\n\nCreate an instance of `NetworkWatchdog` in your context:\n\n```kotlin\nval networkWatchdog = NetworkWatchdog(context)\n```\n\n### **Step 2: Integrate ConnectivityViewModel**\n\nUse the **ConnectivityViewModel** to manage network state. Initialize it in your activity or fragment with the following factory method:\n\n```kotlin\nprivate val connectivityViewModel: ConnectivityViewModel by viewModels {\n    ConnectivityViewModelFactory(NetworkWatchdog(this))\n}\n```\n\n### **Step 3: Monitor Network State**\n\nYou can choose between **callback-based monitoring** or **StateFlow-based observation**.\n\n#### **Method 1: Callback-based Network Monitoring**\n\nUse `startWatching()` to provide specific actions based on the network state (e.g., connected, disconnected, no internet access):\n\n```kotlin\nconnectivityViewModel.startWatching(\n    onConnected = {\n        runOnUiThread { showToast(\"Connected to the Internet\") }\n    },\n    onDisconnected = {\n        runOnUiThread { showToast(\"Disconnected from the Internet\") }\n    },\n    onNoInternetAccess = {\n        runOnUiThread { showToast(\"No Internet Access\") }\n    },\n    onMeteredConnection = {\n        runOnUiThread { showToast(\"Metered Connection\") }\n    },\n    onVPNConnection = {\n        runOnUiThread { showToast(\"VPN Connection\") }\n    }\n)\n```\n\n#### **Method 2: StateFlow-based Network Monitoring**\n\nAlternatively, you can use **StateFlow** for a more declarative approach to network monitoring. Observe network state changes in your UI layer with **lifecycleScope**:\n\n```kotlin\nlifecycleScope.launchWhenStarted {\n    connectivityViewModel.networkState.collect { state -\u003e\n        runOnUiThread {\n            when (state) {\n                is NetworkState.Connected -\u003e updateStatus(\"Connected\")\n                is NetworkState.Disconnected -\u003e updateStatus(\"Disconnected\")\n                is NetworkState.NoInternetAccess -\u003e updateStatus(\"No Internet Access\")\n                is NetworkState.MeteredConnection -\u003e updateStatus(\"Metered Network\")\n                is NetworkState.VPNConnection -\u003e updateStatus(\"VPN Connected\")\n            }\n        }\n    }\n}\n```\n\n---\n\n## **Implementation Details**\n\n### **Network Watchdog**\n\n`NetworkWatchdog` uses **ConnectivityManager** and **NetworkCallback** to listen for network changes. It uses **Flow** to emit updates about network connectivity and internet access, ensuring the device is connected to the internet and not just to a local network.\n\n- **onConnected**: Triggered when the device is connected to a network.\n- **onDisconnected**: Triggered when the device disconnects from any network.\n- **onNoInternetAccess**: Triggered when there is no internet access despite the device being connected to a network.\n- **onMeteredConnection**: Triggered when the device is connected to a metered (pay-per-data) network.\n- **onVPNConnection**: Triggered when the device is connected to a VPN.\n\n### **ConnectivityViewModel**\n\n- **StateFlow Integration**: Exposes network state changes as **StateFlow** for easy observation. It makes sure network state is always updated efficiently, and updates only when the app is in an active lifecycle state.\n- **Caching**: The latest network state is cached using `stateIn`, which prevents redundant emissions and optimizes memory usage.\n- **Lifecycle Awareness**: The **ConnectivityViewModel** automatically manages the start and stop of network monitoring based on the lifecycle of the activity/fragment.\n\n### **UI Safety with `runOnUiThread`**\n\nSince network monitoring and state updates are handled off the main thread, use `runOnUiThread` to ensure that UI updates happen on the main thread, preventing any threading issues when interacting with UI elements.\n\n```kotlin\nrunOnUiThread {\n    // Safely update UI elements\n}\n```\n\n---\n\n## **Advantages of This Approach**\n\n- **Lifecycle Awareness**: Network monitoring automatically adjusts to the lifecycle of your components, ensuring no unnecessary resources are used.\n- **Efficient State Management**: **StateFlow** and `stateIn` help to manage the network state efficiently by reducing redundant emissions.\n- **Scalable and Maintainable**: This design enables you to easily scale network monitoring and integrate it into large applications.\n- **Thread Safety**: Network monitoring runs off the main thread, ensuring your app remains responsive.\n\n---\n\n## **Example Usage**\n\nHere's a complete example using **Network Watchdog** in an activity:\n\n```kotlin\nprivate val connectivityViewModel: ConnectivityViewModel by viewModels {\n    ConnectivityViewModelFactory(NetworkWatchdog(this))\n}\n\noverride fun onCreate(savedInstanceState: Bundle?) {\n    super.onCreate(savedInstanceState)\n    setContentView(R.layout.activity_main)\n\n    // Start watching network state\n    connectivityViewModel.startWatching(\n        onConnected = {\n            runOnUiThread { showToast(\"Connected to the Internet\") }\n        },\n        onDisconnected = {\n            runOnUiThread { showToast(\"Disconnected from the Internet\") }\n        },\n        onNoInternetAccess = {\n            runOnUiThread { showToast(\"No Internet Access\") }\n        },\n        onMeteredConnection = {\n            runOnUiThread { showToast(\"Metered Connection\") }\n        },\n        onVPNConnection = {\n            runOnUiThread { showToast(\"VPN Connected\") }\n        }\n    )\n\n    // Collect network state with StateFlow\n    lifecycleScope.launchWhenStarted {\n        connectivityViewModel.networkState.collect { state -\u003e\n            runOnUiThread {\n                when (state) {\n                    is NetworkState.Connected -\u003e updateStatus(\"Connected\")\n                    is NetworkState.Disconnected -\u003e updateStatus(\"Disconnected\")\n                    is NetworkState.NoInternetAccess -\u003e updateStatus(\"No Internet Access\")\n                    is NetworkState.Metered -\u003e updateStatus(\"Metered Network\")\n                    is NetworkState.VPN -\u003e updateStatus(\"VPN Connected\")\n                }\n            }\n        }\n    }\n}\n```\n\n---\n\n## **Contribution**\n\nContributions are welcome! If you encounter any bugs or have feature requests, feel free to open issues or submit pull requests.\n\n---\n\n## **License**\n\nThis project is licensed under the **MIT License**. See the `LICENSE` file for details.\n\n---\n\n## **Notes**\n\n- Always use **`runOnUiThread`** for UI updates inside network state callbacks.\n- **`ConnectivityViewModel`** ensures lifecycle-safety and efficient network monitoring management.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fstyropyr0%2Fnetworkwatchdog","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fstyropyr0%2Fnetworkwatchdog","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fstyropyr0%2Fnetworkwatchdog/lists"}