Created
May 3, 2020 15:06
-
-
Save Runman44/86dab5a30be785e77309ca410b615212 to your computer and use it in GitHub Desktop.
withContext example
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
suspend fun refreshTitle() { | |
// interact with *blocking* network and IO calls from a coroutine | |
withContext(Dispatchers.IO) { | |
val result = try { | |
// Make network request using a blocking call | |
network.fetchNextTitle().execute() | |
} catch (cause: Throwable) { | |
// If the network throws an exception, inform the caller | |
throw TitleRefreshError("Unable to refresh title", cause) | |
} | |
if (result.isSuccessful) { | |
// Save it to database | |
titleDao.insertTitle(Title(result.body()!!)) | |
} else { | |
// If it's not successful, inform the callback of the error | |
throw TitleRefreshError("Unable to refresh title", null) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment