Chapter 10: Challenge 1 onComplete

To turn off the activity indicator, there is a “.do” subscribed to “onCompleted”. That works as expected. Now, I decided to comment out the “.do” and create another subscription right below it as follows:

 updatedCategories.subscribe(onCompleted: {
        print("DONE")
        DispatchQueue.main.async { [weak self] in
            self?.activityIndicator.stopAnimating()
        }
    }).disposed(by: disposeBag)

I figure this should do the same thing but it appears to have a subtle difference. In the debug console window, I see the “DONE” print and then I see another call to the interface (example below–I’ve shortened the link so I could post)

curl -X GET
“8?status=closed&days=360” -i -v
Success (2737ms): Status 200
DONE
curl -X GET
“8?status=closed&days=360” -i -v
Success (2610ms): Status 200

I thought it might be a timing issue but it happens in this exact order every time. If I comment out my code and put back the “.do” with a print statement, it works as expected.

 .do(onCompleted: { [weak self] in
        print("IM DONE HERE")
      DispatchQueue.main.async {
        self?.activityIndicator.stopAnimating()
      }
    })

curl -X GET
“8?status=closed&days=360” -i -v
Success (2181ms): Status 200
IM DONE HERE

If I keep in the “.do” and also my new subscription then the results are completely unexpected.

curl -X GET
“8?status=closed&days=360” -i -v
Success (2582ms): Status 200
IM DONE HERE
DONE
curl -X GET
“8?status=closed&days=360” -i -v
Success (2372ms): Status 200
IM DONE HERE

I’m confused why I would see the “.do” executed twice and why the “DONE” appears to be displayed even though it doesn’t really appear to be done. Also, why does adding another subscription apparently change the ordering of events–meaning I’m getting multiple onCompleted events.

@fpillet Can you please help with this when you get a chance? Thank you - much appreciated! :]

Hi @dfrobison,

By subscribing a second time to the updatedCategories observable, you created a second subscription to downloadedEvents which in turn calls EONET.events to obtain events. This last one triggers the web request. Since you have a second subscription, remember that each subscription (unless using the share() operator) triggers a subscription to the whole chain up to the original observable.

The reason you’re seeing the DONE message displayed in-between the two prints are possibly due to a faster completion of the first request, maybe due to inbuilt web caches in URLSession. Unless you manually set caching options, you’re using the default settings here.

Please let me know if this explanation makes sense and is clear enough for you.

Thanks. That was it. I forgot to share the subscription. When I shared it, it now works as expected.

This topic was automatically closed after 166 days. New replies are no longer allowed.