flatMap(to: View.self) multiple times in Leaf examples

func userHandler(_ req: Request) throws -> Future<View> {
  // 2
  return try req.parameters.next(User.self)
    .flatMap(to: View.self) { user in
// 3
      return try user.acronyms
        .query(on: req)
        .all()
        .flatMap(to: View.self) { acronyms in
// 4
          let context = UserContext(
            title: user.name,
            user: user,
            acronyms: acronyms)
          return try req.view().render("user", context)
     }
} }

In this code example, flatMap(to: View.self) happens twice. I was wondering why and if that is needed? I understand that you need to unwrap the user, and then unwrap the acronyms. But do both need to be flatMapped to a View.self? Thank you.

@0xtim Can you please help with this when you get a chance? Thank you - much appreciated! :]

@crystaltwix yes, both need to be flatMapped to View.self. The reason for this is that the closure from req.parameters.next(User.self).flatMap must return View.self). In order for theuser.acronyms.query(on: req).all()to returnView.self(since that is what you return) then this must flatMap toView.self. Theto` parameter just defines the return type of the closure. Does that make sense?

Normally, you could chain the different futures, but since you need the user and acronyms for the context and you need the resolved user to get the acronyms, there’s no nice way to tidy it up