https://github.com/jimmymcbride/networkstateutilslib
https://github.com/jimmymcbride/networkstateutilslib
Last synced: 3 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/jimmymcbride/networkstateutilslib
- Owner: JimmyMcBride
- Created: 2023-05-20T17:45:30.000Z (about 2 years ago)
- Default Branch: trunk
- Last Pushed: 2023-05-21T06:12:31.000Z (about 2 years ago)
- Last Synced: 2025-01-15T13:10:05.798Z (5 months ago)
- Language: Kotlin
- Size: 110 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Network State Utils
Network state utils package is just a small package that offers some tools to make handling network
states and events a breeze!## Installation
To install simply add the package to your dependencies add jitpack to root build gradle:
```groovy
allprojects {
repositories {
// ...
maven { url 'https://jitpack.io' }
}
}
```Then add the dependency to your module gradle.
```groovy
dependencies {
implementation 'com.github.JimmyMcBride:NetworkStateUtilsLib:1.0.1'
}
```## NetworkState
`NetworkState` is a sealed class to handle... you guessed it, our network state.
```kotlin
sealed class NetworkState {
object Idle : NetworkState()
object Loading : NetworkState()
data class Success(val data: T) : NetworkState()
data class Error(val message: String) : NetworkState()
}
```## duringState
`duringState` is an extension function for `NetworkState` that helps us handle what happens during
any given state the network request is in.```kotlin
networkEvent.duringState(
success = { data -> onSuccess(data) },
error = { message -> onError(message) },
loading = { onLoading() },
idle = { onIdle() }
)
```## DuringComposableState
Very similar to `duringState` but allows you to add composable functions inside each state block.
```kotlin
networkEvent.DuringComposableState(
success = { data ->
Text(data.name)
},
error = { message ->
Text("N/A")
showSnackbar(message)
},
loading = { CircularProgressIndicator() },
idle = {}
)
```## ConsumeNetworkEvent
Sometimes you'll want to reset the `NetworkState` back to Idle after a specific even has occurred. Be
sure to include a clean up function resetting `NetworkState` back to idle in the view model for
`ConsumeNetworkEvent` to use.```kotlin
@HiltViewModel
class CitiesViewModel @Inject constructor(
private val cityUseCases: CityUseCases
) : ViewModel() {
private var _cities = cityUseCases.getCitiesUseCase(viewModelScope)
val cities: State>> = _citiesprivate val _addCityEvent = mutableStateOf>(NetworkState.Idle)
val addCityEvent: State> = _addCityEventfun addCity(city: CityBody) {
_addCityEvent.value = NetworkState.Loading
viewModelScope.launch {
delay(2000L)
_addCityEvent.value = cityUseCases.addCityUseCase(city).duringState(
success = {
fetchCities()
}
)
}
}fun consumeAddCityEvent(triggeredBlock: () -> Unit) {
triggeredBlock()
_addCityEvent.value = NetworkState.Idle
}
}
``````kotlin
ConsumeNetworkEvent(
networkEvent = addCityEvent,
consumeEvent = citiesViewModel::consumeAddCityEvent,
onSuccess = {
isLoading = false
navController.popBackStack()
},
onError = {
isLoading = false
},
onLoading = { isLoading = true }
)
```## handleNetworkException and handleResponse
`handleNetworkException` and `handleResponse` are just some small utils to help up clean up our
repository.```kotlin
fun Response.handleResponse(errorMessage: String = "Something went wrong.") =
if (this.isSuccessful && this.body() != null)
NetworkState.Success(data = this.body()!!)
else
NetworkState.Error(message = errorMessage)suspend fun handleNetworkException(apiCall: suspend () -> NetworkState) = try {
apiCall()
} catch (e: Exception) {
NetworkState.Error(message = e.message.toString())
}
``````kotlin
class RepositoryImpl(
private val citiesApi: CitiesApi,
) : Repository {
override suspend fun getCities(): NetworkState> =
handleNetworkException { citiesApi.getCites().handleResponse() }
}
```If you have any questions feel free to email me @ [email protected] or leave an issue on this
repository if you notice and bugs or have any requests.