Created
January 11, 2024 07:04
-
-
Save mo7amd89/d57c68d1150f26bf937d330161354d3f to your computer and use it in GitHub Desktop.
Handle api call Android kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.coroutines.* | |
// this code snipped from Vengatesh M.’s Post https://www.linkedin.com/feed/update/urn:li:activity:7150818581406994432/ | |
fun main() { | |
val viewmodel = ViewModel() | |
runBlocking { | |
viewmodel.getDataFromApi() | |
} | |
} | |
// Modelling api states | |
sealed class ApiResult<out T> { | |
data class Success<out T>(val data: T) : ApiResult<T>() | |
data class Failure(val exception: Exception) : ApiResult<Nothing>() | |
fun onSuccess(block: (T) -> Unit): ApiResult<T> { | |
if (this is Success) { | |
block(this.data) | |
} | |
return this | |
} | |
fun onFailure(block: (Exception) -> Unit): ApiResult<T> { | |
if (this is Failure) { | |
block(this.exception) | |
} | |
return this | |
} | |
} | |
// Repository | |
class Repository { | |
suspend fun getDataFromApi(): ApiResult<String> { | |
return try { | |
delay(1000L) | |
// Simulate a successful network call | |
val responseData = "Data from api" | |
ApiResult.Success(responseData) | |
} catch (e: Exception) { | |
// Simulate a failed network call | |
ApiResult.Failure(e) | |
} | |
} | |
} | |
// ViewModel | |
class ViewModel { | |
private val repository = Repository() | |
suspend fun getDataFromApi() { | |
repository.getDataFromApi() | |
.onSuccess { data -> | |
println(data) | |
} | |
.onFailure { e -> | |
println(e.localizedMessage) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment