Skip to content

Instantly share code, notes, and snippets.

@objcode
Created May 21, 2019 02:12
Show Gist options
  • Save objcode/5bad5494723cf06f33d15e588c1dcaf8 to your computer and use it in GitHub Desktop.
Save objcode/5bad5494723cf06f33d15e588c1dcaf8 to your computer and use it in GitHub Desktop.
Use afterPrevious to ensure one sort runs at a time.
// Solution #2: Add a Mutex
// Note: This is not optimal for the specific use case of sorting
// or filtering but is a good pattern for network saves.
class ProductsRepository(val productsDao: ProductsDao, val productsApi: ProductsService) {
val singleRunner = SingleRunner()
suspend fun loadSortedProducts(ascending: Boolean): List<ProductListing> {
// wait for the previous sort to complete before starting a new one
return singleRunner.afterPrevious {
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