Muhammad Usman
04/17/2021, 12:57 PMopen class RootResponse<T> {
var success: Boolean = false
var msg: String? = null
var data: T? = null
}
fun <E, T : RootResponse<E>> CoroutineScope.launchCatching(blk: suspend () -> T): Result<E> {
this.launch {
kotlin.runCatching { blk() }
.onSuccess {
if (it.success && it.data != null) {
Result.success(it.data)
} else {
Result.failure<String>(Throwable(it.msg))
}
}.onFailure {
Result.failure<String>(it)
}
}
}
Dominaezzz
04/17/2021, 1:16 PMlaunchCatching
to do exactly? You've broken quite a few conventions here, so I'm not sure.rkeazor
04/18/2021, 3:01 PMDominaezzz
04/18/2021, 3:02 PMrkeazor
04/18/2021, 3:10 PMMuhammad Usman
04/19/2021, 3:44 AMMuhammad Usman
04/19/2021, 3:44 AM@FormUrlEncoded
@POST("mobile/auth/login")
suspend fun login(
@Field("username") email: String,
@Field("password") password: String,
): RootResponse<UserModel>
fun callApiOld() {
lifecycleScope.launch {
kotlin.runCatching {
WebService.getInstance().login("email", "pass")
//suspendable retrofit api call
}.onSuccess {
if (it.success && it.data != null) {
//handle succes
} else {
it.msg //handle error
}
}.onFailure {
//handle error
}
}
}
fun callApiNew() {
lifecycleScope.launchCatching {
WebService.getInstance().login("email", "pass")
}.onSuccess { userModel->
//use user model here mean actual response from api
}.onFailure {
//handle error
}
}
uli
04/19/2021, 4:36 PMuli
04/19/2021, 4:38 PMCoroutineScope.launchCatching
a suspend fun and remove the launch