Skip to content

Instantly share code, notes, and snippets.

@objcode
Created May 21, 2019 02:18
Show Gist options
  • Save objcode/5b9e6e2d7822052e304abb999c641b1a to your computer and use it in GitHub Desktop.
Save objcode/5b9e6e2d7822052e304abb999c641b1a to your computer and use it in GitHub Desktop.
Run one network request at a time using joinOnPrevious
class ProductsRepository(val productsDao: ProductsDao, val productsApi: ProductsService) {
var controlledRunner = ControlledRunner<List<ProductListing>>()
suspend fun fetchProductsFromBackend(): List<ProductListing> {
// if there's already a request running, return the result from the
// existing request. If not, start a new request by running the block.
return controlledRunner.joinPreviousOrRun {
val result = productsApi.getProducts()
productsDao.insertAll(result)
result
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment