Need help understanding map with bool value (Ch. 13.)

In chapter 13 there is this bit of code:

let running = Observable.merge(
    searchInput.map { _ in true },
    search.map { _ in false }.asObservable()
  )
  .startWith(true)
  .asDriver(onErrorJustReturn: false)

And the explanation for it is as follows:
" The two observables searchInput and search can be merged into a single observable having the value of either true or false depending on whether or not they are receiving events. The result is an observable describing whether the application is currently requesting data from the server or not."

What I’m not completely getting is why searchInput is mapped to “_ in true”, while search is mapped to “_ in false”. Since the activity indicator should only be shown when the user is not entering text and the data is being retrieved from the api, I’m assuming that when the user is inputting text, searchInput is mapped to false and while data is being retrieved from the api, is search mapped to true. Is this correct?

That’s a great point, you are completely right that the name is somewhat confusing.

If you look few paragraphs further in the chapter you will see that running is bound to the isHidden property on the views. In other words when running is true - the activity is hidden… In this case the issue is somewhat poor naming of the variable. If it was called isNotSearching would’ve been more semantic and easier to understand.

1 Like

Ah that makes more sense. I was so hung-up on that code fragment that I missed that. I think the syntax of “_ in true”, “_ in false” was also throwing me off. Does this mean that if the searchInput is active that “true in true”. i.e. “true” is returned, and when the search is active “true in false”, i.e “false” is returned?

yeah, _ in X is basically a constant, the closure returns X whatever the input is. This is a common pattern, especially if you combine streams of values.

1 Like

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