J'ai besoin de remplir la liste des objets de DB. Et avant de passer de la valeur aux éléments, je veux qu'ils se terminent tous. Y a-t-il ici un appel abrégé en attente () pour chaque élément à attendre. Je veux créer du code propre, peut-être un modèle de conception ou une astuce?
for (x in 0..10) { launch { withContext(Dispatchers.IO){ list.add(repository.getLastGame(x) ?: MutableLiveData<Task>(Task(cabinId = x))) } } } items.value = list
3 Réponses :
IntRange( 0, 10 ).map { async { // Logic } }.forEach { it.await() }
coroutineScope { // limits the scope of concurrency (0..10).map { // is a shorter way to write IntRange(0, 10) async(Dispatchers.IO) { // async means "concurrently", context goes here list.add(repository.getLastGame(x) ?: MutableLiveData<Task>(Task(cabinId = x))) } }.awaitAll() // waits all of them } // if any task crashes -- this scope ends with exception
Voici un exemple, similaire aux autres, à utiliser avec les instantanés Firestore.
listOf(AnnualReport(...), AnnualReport(...))
Renvoie:
XXX
1) Votre référentiel est-il un singleton? 2) Où lancez-vous cette coroutine? Dans ViewModel?
oui ça singleton et ça à l'intérieur de ViewModel