Last active
June 19, 2019 09:56
-
-
Save Tougee/8fea4bf1bb270ed5b4fa184a675d871e to your computer and use it in GitHub Desktop.
Handle network response provide by Retrofit suspend style function
This file contains 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
fun fetchFoo() = GlobalScope.launch { | |
handleNetworkResponse<Foo, Unit>( | |
invokeNetwork = { | |
fooService.fetchFoo() | |
}, | |
successBlock = { r -> | |
// success logic | |
}, | |
errorBlock = { | |
// error logic | |
}, | |
exceptionBlock = { | |
// exception logic | |
} | |
) | |
} | |
interface FooService { | |
@GET("foo") | |
suspend fun fetchFoo(): NetworkResponse<Foo> | |
} | |
This file contains 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
suspend fun <T, R> handleNetworkResponse( | |
invokeNetwork: suspend () -> NetworkResponse<T>, | |
switchContext: CoroutineContext? = null, | |
successBlock: (suspend (NetworkResponse<T>) -> R)? = null, | |
errorBlock: (() -> R)? = null, | |
exceptionBlock: (() -> R)? = null | |
): R? { | |
val response = if (switchContext != null) { | |
try { | |
withContext(switchContext) { | |
invokeNetwork() | |
} | |
} catch (t: Throwable) { | |
// default logic like handleException(t) | |
return exceptionBlock?.invoke() | |
} | |
} else { | |
try { | |
invokeNetwork() | |
} catch (t: Throwable) { | |
// default logic like handleException(t) | |
return errorBlock?.invoke() | |
} | |
} | |
return if (response.isSuccess) { | |
successBlock?.invoke(response) | |
} else { | |
// default logic like handleErrorCode(response.errorCode) | |
errorBlock?.invoke() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment