Skip to content

Instantly share code, notes, and snippets.

@objcode
Created May 21, 2019 02:03
Show Gist options
  • Save objcode/dd3fe2839e8ddc53b9be13d7bc4bcfb7 to your computer and use it in GitHub Desktop.
Save objcode/dd3fe2839e8ddc53b9be13d7bc4bcfb7 to your computer and use it in GitHub Desktop.
Use cancelPreviousThenRun to control concurrency
// Solution #1: Cancel previous work
// This is a great solution for tasks like sorting and filtering that
// can be cancelled if a new request comes in.
class ProductsRepository(val productsDao: ProductsDao, val productsApi: ProductsService) {
var controlledRunner = ControlledRunner<List<ProductListing>>()
suspend fun loadSortedProducts(ascending: Boolean): List<ProductListing> {
// cancel the previous sorts before starting a new one
return controlledRunner.cancelPreviousThenRun {
if (ascending) {
productsDao.loadProductsByDateStockedAscending()
} else {
productsDao.loadProductsByDateStockedDescending()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment