.map & .flatMap with Future/EventLoopFuture

Hello so I'm a beginner in Swift and my first dive into it has been with Vapor 4.

One thing that has been confusing me has been using the Client API (https://docs.vapor.codes/4.0/client/) which returns an EventLoopFuture/Future upon making a GET/POST/etc. request. I'm confused why .map makes sense to resolve the request.

Ex.

    req.client.get("https://httpbin.org/status/200").map { res in
        // Handle the response.
    }

Coming from JavaScript promises, I see the need for a method to take in a callback such as .then in JS, but .map or .flatMap seems strange given that I'm not being given a collection type (array) but rather a single response object.

Another example of using .map and .flatMap in a similar way to JS .then:

req.client.get("https://httpbin.org/json").flatMapThrowing { res in
    try res.content.decode(MyJSONResponse.self)
}.map { json in
    // Handle the json response.
}

Once again the thing that sticks out to me above is that both res and json are single objects.

Here's a similar way of doing this in JS:

fetch('http://example.com/movies.json')
  .then(response => response.json())
  .then(data => console.log(data));

In summary, would be happy to hear why .map makes sense in idiomatic Swift to be both used for handling collection type transformation (ex. [1,2,3,4].map { $0 + 1 }) and also as a .then (in JS terms).

Thanks!

Those aren't collections' idioms. They're much closer to wrapper's like Optional's, map and flatMap.

3 Likes

@Lantua thanks! That clarifies a lot. I wasn't even aware that Optionals (as a broad programming construct/idea) used .map & .flatMap in its terminology.

Well, I don't actually know if the term applies to concept of Optional in general outside of Swift, but they're the names most (Swift) wrapper types, including Optional and Publisher choose.

1 Like

AFAIK these are more of terms of art in the functional programming world with the concepts of monads.

map and flatMap have the same basic operation, but different semantic meanings based on the "monad" (Optional, EventLoopFuture, etc.) in question

4 Likes

Result and Publisher are also good examples here. Personally to me, the meaning is the same regardless of the type:

  • map takes the element out of the "container", transforms it, and puts it back into the same container.
  • flatMap takes the element ouf of the "container", transforms it to a new container, puts it back, and flattens the result to avoid double-wrapping.

It doesn't matter if your container is a collection, or a "single-element container" like Future, Optional, or Result, the principles are the same, so it makes sense for the names to stay the same across all these types.

4 Likes

@Mordil @Max_Desiatov thanks for the answers! They definitely helped me stretch some of my limited FP knowledge & definitions.

1 Like
Terms of Service

Privacy Policy

Cookie Policy