Created
November 17, 2018 14:33
-
-
Save mayojava/dbf6d8e4d706becafe35c5a9a5f706e2 to your computer and use it in GitHub Desktop.
coroutine demonstration
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
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