Search with RxSwift

Pedro Henrique
2 min readDec 15, 2017

If you’ve ever had a problem developing an IOS application that performs searches, know that using RxSwift and RxCocoa your work could have been simpler. I will show you a simple and direct way of doing this. (I assume that you know the basics of RxSwift and RxCocoa).

To start, let’s imagine that we have an API that returns the current season stats of an NFL player.

struct NflPlayerStats: Codable {
var playerName: String
var gamesPlayed: Int
var touchdowns: Int
var yards: Int
}

This is the NflPlayerStats struct, it is a Codable. We will use this to handle the API response. This API prefers offensive players :)

Now let’s create the class that will make the API calls.

The urlString() receives a String as parameter, which would be the search term, and returns a url. In this function, first, we use the addingPercentEncoding(), With this we can avoid that there are spaces between the words of the search term, because if they exist, they may generate a error. So, instead of the term being "Tom Brady", it will be changed to "Tom%20Brady". After this, the function continues with the creation of the url, concatenating the search term to url.

The next is the parse(data:) function. This function decodes the JSON data that will be returned by de API to a NflPlayerStats format.

Last but not least, the search() function, that will make API calls. This function will be called from the ViewController, where are UITableView and UISearchBar. Here we start using the RxSwift. We return a Observable of type NflPlayerStats. To do this, we created an URLSession.shared and used a rx.data(request: ), passing an URLRequest for it. The return of this call is passed to parse().

Now let’s talk about the ViewController. First, you need to create a DisposeBag

let disposeBag = DisposeBag()

Now let’s create the function that will handle the RxSwift and RxCocoa for us. This function should be called from your viewDidLoad()

In this code, first is manipulating what is typed in the search bar and this is passed to the ApiController.shared.search(search:). The return of ApiController.shared.search(search:) is stored in the variable results.

After this, we have to populate the UITableView. So the bind is used. I recommend that you create a class to manipulate the properties of your cell if you have chosen to create them in an xib. In this way, in this example, the returned data is passed to the cell setup function.

That’s it. Now you should have a dynamic search like this one here.

If you are interested in learning or increasing your knowledge related to RxSwift and RxCocoa, I recommend you buy the book RxSwift, from raywenderlich.com. For this tutorial, I used this book and IOS Apprentice. I also recommend reading this article or this one, they helped me to understand some concepts.

Thanks for reading, I hope this helps you. If you know another way to do this, please leave your comment.

--

--