Skip to content

Instantly share code, notes, and snippets.

@antarikshc
Created August 27, 2019 20:19
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save antarikshc/4103c5a0bd4651e0522fdd3b06b449cd to your computer and use it in GitHub Desktop.
Synchronized Apollo Requests with Coroutines inside WorkManager
class DemoWorker(appContext: Context, workerParams: WorkerParameters) :
Worker(appContext, workerParams) {
override fun doWork(): Result {
....
// Synchronous Apollo request
val result = runBlocking {
try {
val response = client.mutate(
UpdateUserMutation.builder()
.user(userInput)
.build()
).execute()
if (!response.hasErrors()) {
// Get response body in response.data()
Result.success()
} else {
Result.failure()
}
} catch (e: Exception) {
Result.retry()
}
}
return result
}
}
// Coroutines Extension function for making Synchronous ApolloCall's
suspend fun <T> ApolloCall<T>.execute() = suspendCoroutine<Response<T>> { cont ->
enqueue(object : ApolloCall.Callback<T>() {
override fun onResponse(response: Response<T>) {
cont.resume(response)
}
override fun onFailure(e: ApolloException) {
cont.resumeWithException(e)
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment