Skip to content

Instantly share code, notes, and snippets.

@mayojava
Created November 17, 2018 14:33
Show Gist options
  • Save mayojava/dbf6d8e4d706becafe35c5a9a5f706e2 to your computer and use it in GitHub Desktop.
Save mayojava/dbf6d8e4d706becafe35c5a9a5f706e2 to your computer and use it in GitHub Desktop.
coroutine demonstration
class CoroutinesPresenter(private val dispatcherProvider: DispatchersProvider,
private val repository: Reviewsrepository) {
private val job = Job()
private val uiScope = CoroutineContext(dispatcherProvider.main + job) //runs on main thread
fun fetchData(count: Int, page: Int) {
try {
uiScope.launch {
arbitraryView.setLoading(true)
//switch to IO thread
val reviews = withContext(dispatcherProvider.io()) {
repository.fetchReviews(count, page)
}
arbitraryView.updateReviewsList(data)
}
} catch(e: Exception) {
arbitraryView.updateUiForError(e)
} finally {
arbitraryView.setLoading(false)
}
}
//or any function that depicts the presenter is getting destroyed or detached from view
//this will be on Cleared in arch component ViewModel
fun onDestroy() {
job.cancel()
}
}
data class DispatchersProvider(
val io: CoroutineDispatcher = Dispatchers.IO,
val main: CoroutineDispatcher = Dispatchers.MAIN,
val computation: CoroutineDispatcher = Dispatchers.DEFAULT
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment