Incremental Search with multibyte text in RxSwift/RxCocoa

Ryo ishikawa
Jul 22, 2017 · 2 min read

Incremental search is currently used various apps. The way to search something is generally using UISearchBar. If you use reactive extension libraries such as RxSwift and RxCocoa, you can use rx.text property to detect latest text in UISearchBar, but in case of use multibyte text, it is not possible because there are input conversion and the text is still undetermined.

This is only cause using UISearchBar , UITextField is able to detect the latest text even text is undetermined.

Don’t worry, There is a way to make incremental search using UISearchBar. This is the sample code:

First of all, Set a delegate in your UISearchBar, after that add this delegate method in your ViewController. This delegate method represents that the current undetermined input text should replace to current text or not by returning value. After returning true, you can access the latest text as searchBar.text. But it is necessary to wait a little interval to update the text property.

Next, Add property used for incremental search like this.

Now you can detect the latest text from UISearchBar using incrementalText .

methodInvoked operator called when the designated delegate method is finished. debounce operator has two roles in this case, One is waiting for update the text property. The other is filtering user input between 0 to 0.2 seconds.

Using Rx in this way makes it easy to handle complex processing with readability by only declarar one place.

References:
https://developer.apple.com/documentation/uikit/uisearchbardelegate/1624328-searchbar
https://github.com/ReactiveX/RxSwift
https://github.com/ReactiveX/RxSwift/tree/master/RxCocoa