Created
November 28, 2020 15:51
-
-
Save BurakDizlek/28289a0ca9ec377b0bd3f735afab7faa to your computer and use it in GitHub Desktop.
Sealed class usage with api calls simplest
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
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