Activity Indicator in RxSwift using amb()

Manish Singh
3 min readJan 17, 2021

--

I have been working on some of my projects and stumbled upon how to properly handle UIActivityIndicator loading state while the API call is in progress in RxSwift. While doing some research I found this article https://www.thomasvisser.me/2016/08/03/rxswift-loading/. In this write up the author has shown how amb() can be helpful in determining which state to show based on which observable emits event first.

From amb() documentation

When you pass a number of source Observables to Amb, it will pass through the emissions and notifications of exactly one of these Observables: the first one that sends a notification to Amb, either by emitting an item or sending an onError or onCompleted notification. Amb will ignore and discard the emissions and notifications of all of the other source Observables.

That’s what I wanted, though, it did not make sense for the first time when I read it, which is true about Rx, In my opinion. Well, anyway, I used this function to show and hide ActivityIndicator based on the state of available data.

In this function, I am fetching some data from API and creating two observables one for the lodingState and another one for the actual data, which will be available after sometime.

In this screenshot, we can see that the loading state appears first followed by a popover for a successful response. This is happening because loading state is emitting events first since actual data is not available at this time from the API. Once the data is available amb() returns data state and based on that we will hide our spinner here.

spinner appears first and then we show this pop over.

error state: This is the case where we will show an alert view with error message, if API returns an error.

Error state

This how all show/hide logic is handled at the subscription level.

Conclusion

I have documented my code here https://github.com/singh88/RxSwiftTestProject and this is the main file line https://github.com/singh88/RxSwiftTestProject/blob/main/RxSwiftTestProject/ViewController.swift#L27. Hopefully, this write up will help someone. Please let me know if you have any further suggestions for this in terms of improvements.

--

--

Responses (1)