Skip to content

Instantly share code, notes, and snippets.

@BurakDizlek
Created November 28, 2020 15:51
Show Gist options
  • Save BurakDizlek/28289a0ca9ec377b0bd3f735afab7faa to your computer and use it in GitHub Desktop.
Save BurakDizlek/28289a0ca9ec377b0bd3f735afab7faa to your computer and use it in GitHub Desktop.
Sealed class usage with api calls simplest
package com.bd.network
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val response = fetchData()
when (response) {
is NetworkResponse.Failed -> {
val message = response.message
val code = response.code
}
is NetworkResponse.Success<*> -> {
val data = response.data as String
}
}
}
fun fetchData(): NetworkResponse {
val isServiceResponseSuccess = true
if (isServiceResponseSuccess) {
return NetworkResponse.Success("Success data")
} else {
return NetworkResponse.Failed("sıkıntı büyük baba","MOB6060")
}
}
}
sealed class NetworkResponse {
class Success<T>(val data: T) : NetworkResponse()
class Failed(val message: String,val code: String) : NetworkResponse() // can be 401, 404 or specific error code
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment