Skip to content
This repository was archived by the owner on May 17, 2023. It is now read-only.

Commit a309483

Browse files
committed
Updated the text after a better 'callbacks' solution was highlighted
kotlin-hands-on/intro-coroutines#22
1 parent 0fde4c6 commit a309483

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

Introduction to Coroutines and Channels/03_UsingCallbacks.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,27 @@ for (repo in repos) {
179179
Note that we're using a synchronized version of the list and `AtomicInteger`, since in general there's no guarantee
180180
that different callback processing `getRepoContributors` requests will always be called from the same thread.
181181

182+
#### Solution (third attempt)
183+
184+
Even a better solution is to use the `CountDownLatch` class.
185+
`CountDownLatch` stores a counter which we initialize with the number of repositories.
186+
We decrement this counter after processing each repository and then wait until the latch has counted down to zero
187+
before updating the results:
188+
189+
```kotlin
190+
val countDownLatch = CountDownLatch(repos.size)
191+
for (repo in repos) {
192+
service.getRepoContributorsCall(req.org, repo.name).onResponse { responseUsers ->
193+
// processing repository
194+
countDownLatch.countDown()
195+
}
196+
}
197+
countDownLatch.await()
198+
updateResults(allUsers.aggregate())
199+
```
200+
201+
We update the result from the main thread, which is more direct than delegating this logic to the child threads.
202+
182203
You can see that writing the right code with callbacks might be non-trivial and error-prone, especially when
183204
there're several underlying threads and synchronization takes place.
184205
Next, we'll discuss how to implement the same logic using `suspend` functions.

0 commit comments

Comments
 (0)