This repository was archived by the owner on May 17, 2023. It is now read-only.
File tree Expand file tree Collapse file tree 1 file changed +21
-0
lines changed
Introduction to Coroutines and Channels Expand file tree Collapse file tree 1 file changed +21
-0
lines changed Original file line number Diff line number Diff line change @@ -179,6 +179,27 @@ for (repo in repos) {
179
179
Note that we're using a synchronized version of the list and ` AtomicInteger ` , since in general there's no guarantee
180
180
that different callback processing ` getRepoContributors ` requests will always be called from the same thread.
181
181
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
+
182
203
You can see that writing the right code with callbacks might be non-trivial and error-prone, especially when
183
204
there're several underlying threads and synchronization takes place.
184
205
Next, we'll discuss how to implement the same logic using ` suspend ` functions.
You can’t perform that action at this time.
0 commit comments