|
| 1 | +# Example: Online Searching |
| 2 | + |
| 3 | +Let’s say you have a text field, and whenever the user types something into it, |
| 4 | +you want to make a network request which searches for that query. |
| 5 | + |
| 6 | +_Please note that the following examples use Cocoa extensions in [ReactiveCocoa][] for illustration._ |
| 7 | + |
| 8 | +#### Observing text edits |
| 9 | + |
| 10 | +The first step is to observe edits to the text field, using a RAC extension to |
| 11 | +`UITextField` specifically for this purpose: |
| 12 | + |
| 13 | +```swift |
| 14 | +let searchStrings = textField.reactive.continuousTextValues |
| 15 | +``` |
| 16 | + |
| 17 | +This gives us a [Signal][] which sends values of type `String?`. |
| 18 | + |
| 19 | +#### Making network requests |
| 20 | + |
| 21 | +With each string, we want to execute a network request. ReactiveSwift offers an |
| 22 | +`URLSession` extension for doing exactly that: |
| 23 | + |
| 24 | +```swift |
| 25 | +let searchResults = searchStrings |
| 26 | + .flatMap(.latest) { (query: String?) -> SignalProducer<(Data, URLResponse), AnyError> in |
| 27 | + let request = self.makeSearchRequest(escapedQuery: query) |
| 28 | + return URLSession.shared.reactive.data(with: request) |
| 29 | + } |
| 30 | + .map { (data, response) -> [SearchResult] in |
| 31 | + let string = String(data: data, encoding: .utf8)! |
| 32 | + return self.searchResults(fromJSONString: string) |
| 33 | + } |
| 34 | + .observe(on: UIScheduler()) |
| 35 | +``` |
| 36 | + |
| 37 | +This has transformed our producer of `String`s into a producer of `Array`s |
| 38 | +containing the search results, which will be forwarded on the main thread |
| 39 | +(using the [`UIScheduler`][Schedulers]). |
| 40 | + |
| 41 | +Additionally, [`flatMap(.latest)`][flatMapLatest] here ensures that _only one search_—the |
| 42 | +latest—is allowed to be running. If the user types another character while the |
| 43 | +network request is still in flight, it will be cancelled before starting a new |
| 44 | +one. Just think of how much code that would take to do by hand! |
| 45 | + |
| 46 | +#### Receiving the results |
| 47 | + |
| 48 | +Since the source of search strings is a `Signal` which has a hot signal semantic, |
| 49 | +the transformations we applied are automatically evaluated whenever new values are |
| 50 | +emitted from `searchStrings`. |
| 51 | + |
| 52 | +Therefore, we can simply observe the signal using `Signal.observe(_:)`: |
| 53 | + |
| 54 | +```swift |
| 55 | +searchResults.observe { event in |
| 56 | + switch event { |
| 57 | + case let .value(results): |
| 58 | + print("Search results: \(results)") |
| 59 | + |
| 60 | + case let .failed(error): |
| 61 | + print("Search error: \(error)") |
| 62 | + |
| 63 | + case .completed, .interrupted: |
| 64 | + break |
| 65 | + } |
| 66 | +} |
| 67 | +``` |
| 68 | + |
| 69 | +Here, we watch for the `Value` [event][Events], which contains our results, and |
| 70 | +just log them to the console. This could easily do something else instead, like |
| 71 | +update a table view or a label on screen. |
| 72 | + |
| 73 | +#### Handling failures |
| 74 | + |
| 75 | +In this example so far, any network error will generate a `Failed` |
| 76 | +[event][Events], which will terminate the event stream. Unfortunately, this |
| 77 | +means that future queries won’t even be attempted. |
| 78 | + |
| 79 | +To remedy this, we need to decide what to do with failures that occur. The |
| 80 | +quickest solution would be to log them, then ignore them: |
| 81 | + |
| 82 | +```swift |
| 83 | + .flatMap(.latest) { (query: String) -> SignalProducer<(Data, URLResponse), AnyError> in |
| 84 | + let request = self.makeSearchRequest(escapedQuery: query) |
| 85 | + |
| 86 | + return URLSession.shared.reactive |
| 87 | + .data(with: request) |
| 88 | + .flatMapError { error in |
| 89 | + print("Network error occurred: \(error)") |
| 90 | + return SignalProducer.empty |
| 91 | + } |
| 92 | + } |
| 93 | +``` |
| 94 | + |
| 95 | +By replacing failures with the `empty` event stream, we’re able to effectively |
| 96 | +ignore them. |
| 97 | + |
| 98 | +However, it’s probably more appropriate to retry at least a couple of times |
| 99 | +before giving up. Conveniently, there’s a [`retry`][retry] operator to do exactly that! |
| 100 | + |
| 101 | +Our improved `searchResults` producer might look like this: |
| 102 | + |
| 103 | +```swift |
| 104 | +let searchResults = searchStrings |
| 105 | + .flatMap(.latest) { (query: String) -> SignalProducer<(Data, URLResponse), AnyError> in |
| 106 | + let request = self.makeSearchRequest(escapedQuery: query) |
| 107 | + |
| 108 | + return URLSession.shared.reactive |
| 109 | + .data(with: request) |
| 110 | + .retry(upTo: 2) |
| 111 | + .flatMapError { error in |
| 112 | + print("Network error occurred: \(error)") |
| 113 | + return SignalProducer.empty |
| 114 | + } |
| 115 | + } |
| 116 | + .map { (data, response) -> [SearchResult] in |
| 117 | + let string = String(data: data, encoding: .utf8)! |
| 118 | + return self.searchResults(fromJSONString: string) |
| 119 | + } |
| 120 | + .observe(on: UIScheduler()) |
| 121 | +``` |
| 122 | + |
| 123 | +#### Throttling requests |
| 124 | + |
| 125 | +Now, let’s say you only want to actually perform the search periodically, |
| 126 | +to minimize traffic. |
| 127 | + |
| 128 | +ReactiveCocoa has a declarative `throttle` operator that we can apply to our |
| 129 | +search strings: |
| 130 | + |
| 131 | +```swift |
| 132 | +let searchStrings = textField.reactive.continuousTextValues |
| 133 | + .throttle(0.5, on: QueueScheduler.main) |
| 134 | +``` |
| 135 | + |
| 136 | +This prevents values from being sent less than 0.5 seconds apart. |
| 137 | + |
| 138 | +To do this manually would require significant state, and end up much harder to |
| 139 | +read! With ReactiveCocoa, we can use just one operator to incorporate _time_ into |
| 140 | +our event stream. |
| 141 | + |
| 142 | +#### Debugging event streams |
| 143 | + |
| 144 | +Due to its nature, a stream's stack trace might have dozens of frames, which, more often than not, can make debugging a very frustrating activity. |
| 145 | +A naive way of debugging, is by injecting side effects into the stream, like so: |
| 146 | + |
| 147 | +```swift |
| 148 | +let searchString = textField.reactive.continuousTextValues |
| 149 | + .throttle(0.5, on: QueueScheduler.main) |
| 150 | + .on(event: { print ($0) }) // the side effect |
| 151 | +``` |
| 152 | + |
| 153 | +This will print the stream's [events][Events], while preserving the original stream behaviour. Both [`SignalProducer`][SignalProducer] |
| 154 | +and [`Signal`][Signal] provide the `logEvents` operator, that will do this automatically for you: |
| 155 | + |
| 156 | +```swift |
| 157 | +let searchString = textField.reactive.continuousTextValues |
| 158 | + .throttle(0.5, on: QueueScheduler.main) |
| 159 | + .logEvents() |
| 160 | +``` |
| 161 | + |
| 162 | +For more information and advance usage, check the [Debugging Techniques][] document. |
| 163 | + |
| 164 | +[SignalProducer]: Documentation/ReactivePrimitives.md#signalproducer-deferred-work-that-creates-a-stream-of-values |
| 165 | +[Schedulers]: Documentation/FrameworkOverview.md#Schedulers |
| 166 | +[Signal]: Documentation/ReactivePrimitives.md#signal-a-unidirectional-stream-of-events |
| 167 | +[Events]: Documentation/ReactivePrimitives.md#event-the-basic-transfer-unit-of-an-event-stream |
| 168 | +[Debugging Techniques]: Documentation/DebuggingTechniques.md |
| 169 | + |
| 170 | +[retry]: Documentation/BasicOperators.md#retrying |
| 171 | +[flatMapLatest]: Documentation/BasicOperators.md#combining-latest-values |
| 172 | + |
| 173 | +[ReactiveCocoa]: https://github.com/ReactiveCocoa/ReactiveCocoa/#readme |
0 commit comments