Created
May 21, 2019 02:03
-
-
Save objcode/dd3fe2839e8ddc53b9be13d7bc4bcfb7 to your computer and use it in GitHub Desktop.
Use cancelPreviousThenRun to control concurrency
This file contains hidden or 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
// 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