DEV Community

Cover image for πŸŽ‰ Introducing the Fantastic New Network State Utils Library for Android πŸŽ‰
Jimmy McBride
Jimmy McBride Subscriber

Posted on

3

πŸŽ‰ Introducing the Fantastic New Network State Utils Library for Android πŸŽ‰

Hey Android developers! πŸ§‘β€πŸ’»πŸ‘©β€πŸ’» Have you been struggling with network state management in your Android projects? Good news β€” the Network State Utils library is here to simplify the process and offer seamless integration with Jetpack Compose to update your UI! πŸ’ͺπŸ“šπŸ“²

Step 1: Easily Install the Library πŸ“₯

Add the package to your project by first including jitpack in your root build.gradle:

allprojects {
    repositories {
        // ...
        maven { url 'https://jitpack.io' }
    }
}
Enter fullscreen mode Exit fullscreen mode

Then, add the dependency to your module gradle:

dependencies {
    implementation 'com.github.JimmyMcBride:NetworkStateUtilsLib:1.0.1'
}
Enter fullscreen mode Exit fullscreen mode

Step 2: Leverage the NetworkState Sealed Class 🌟

NetworkState helps you manage your network requests' current status. States include Idle, Loading, Success, and Error. Take control of UI updates during specific network states!

sealed class NetworkState<out T> {
    object Idle : NetworkState<Nothing>()
    object Loading : NetworkState<Nothing>()
    data class Success<T>(val data: T) : NetworkState<T>()
    data class Error(val message: String) : NetworkState<Nothing>()
}
Enter fullscreen mode Exit fullscreen mode

Step 3: duringState & DuringComposableState πŸ”€

Using duringState and DuringComposableState, handle what happens at various network states. Achieve seamless integration with classic view models or Jetpack Compose!

networkEvent.duringState(
    success = { data -> onSuccess(data) },
    error = { message -> onError(message) },
    loading = { onLoading() },
    idle = { onIdle() }
)
Enter fullscreen mode Exit fullscreen mode
networkEvent.DuringComposableState(
    success = { data ->
        Text(data.name)
    },
    error = { message ->
        Text("N/A")
        showSnackbar(message)
    },
    loading = { CircularProgressIndicator() },
    idle = {}
)
Enter fullscreen mode Exit fullscreen mode

Step 4: ConsumeNetworkEvent πŸ”„

Use ConsumeNetworkEvent to reset NetworkState back to Idle after a specific event. It resets the state, ensuring your UI remains fresh for subsequent updates!

ConsumeNetworkEvent(
    networkEvent = addCityEvent,
    consumeEvent = citiesViewModel::consumeAddCityEvent,
    onSuccess = {
        isLoading = false
        navController.popBackStack()
    },
    onError = {
        isLoading = false
    },
    onLoading = { isLoading = true }
)
Enter fullscreen mode Exit fullscreen mode

Step 5: Simplify with handleNetworkException & handleResponse πŸ› οΈ

Simplify your repository by using handleNetworkException and handleResponse for managing exceptions and responses during API calls.

fun <T> Response<T>.handleResponse(errorMessage: String = "Something went wrong.") =
    if (this.isSuccessful && this.body() != null)
        NetworkState.Success(data = this.body()!!)
    else
        NetworkState.Error(message = errorMessage)

suspend fun <T> handleNetworkException(apiCall: suspend () -> NetworkState<T>) = try {
    apiCall()
} catch (e: Exception) {
    NetworkState.Error(message = e.message.toString())
}
Enter fullscreen mode Exit fullscreen mode

With Network State Utils, you have a powerful and accessible library to manage network events in your Android applications. Empower your code and simplify your network state management!

What are your thoughts on the Network State Utils library? Feel free to ask questions or leave comments below! And don't forget to hit that Like button and follow for more awesome content! πŸ€©πŸ‘

Sentry mobile image

Improving mobile performance, from slow screens to app start time

Based on our experience working with thousands of mobile developer teams, we developed a mobile monitoring maturity curve.

Read more

Top comments (2)

Collapse
 
erdo profile image
Eric Donovan β€’

Nice πŸ‘πŸ‘πŸ‘ I reckon you might be able to get it to support ktor as well as retrofit by providing an alternative handleResponse function btw (and if you reference retrofit in the build grade with api rather than implementation, that should mean users won't need to pull in retrofit if they don't use it) and congrats on releasing it! 99% of devs don't get that far ;)

Collapse
 
jimmymcbride profile image
Jimmy McBride β€’

That's actually a really good idea! Thanks for the insight! One thing I want to do as well is make the Error type more dynamic. People (or me) might want to handle errors in a more robust way.

I'm thinking of making an empty Error interface for the Error type instead of string. That way people can create their own custom Error types and just extend the interface to build their own custom implementations.

Building out support for retrofit and ktor is actually a beautiful idea. Could really flesh this out into a super useful tool!

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit