Last active
June 18, 2019 16:11
-
-
Save amanjeetsingh150/1d9015787faa67cdfecf4b6c1d1418d7 to your computer and use it in GitHub Desktop.
Zipping analogy with Coroutines
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
private val zipDataChannel = Channel<List<FeedItem>>(2) | |
// Async coroutine builder for latest movies | |
fun loadLatestMoviesAsync() = | |
scope.async(coroutinesDispatcherProvider.io) { | |
moviesRepository.getLatestMovies()?.let { | |
zipDataChannel.send(it) | |
} | |
} | |
// Async coroutine for popular movies | |
fun loadPopularMoviesAsync() = | |
scope.async(coroutinesDispatcherProvider.io) { | |
moviesRepository.getPopularMovies()?.let { | |
zipDataChannel.send(it) | |
} | |
} | |
// Consuming the zipped data and sending in callback | |
fun zipMovieResults() = scope.launch(coroutinesDispatcherProvider.io) { | |
for (values in zipDataChannel) { | |
totalResults.add(values) | |
} | |
onDataLoadedCallback?.onDataLoaded(totalResults) | |
} |
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
private fun zip(vararg anyObjects: Unit?, call: (Any) -> Unit) { | |
call(anyObjects) | |
// closes channel | |
dataManager.closeChannel() | |
} | |
private fun loadData() = scope.launch { | |
// Await till these two call finishes | |
zip( | |
dataManager.loadLatestMoviesAsync().await(), | |
dataManager.loadPopularMoviesAsync().await(), | |
) { | |
// Consumes value from channel internally | |
dataManager.zipMovieResults() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment