title: Map vs FlatMap in Spring Web Flux and Reactor
body: <p>I have been working on a sample reactive web api using Spring Boot 2.0.1 and its Webflux library. I have been looking at examples from online to try to build it, but I am stumped on two things. Below are the two questions I have.</p>
  
  <p>1) How do I return a Flux of Response Entities, when I try I get an error saying that only a Single Response Entity can be returned. Below is my current code.</p>
  
  <pre><code>@Service
  public class MovieServiceImpl implements MovieService {
  
      @Autowired
      private MovieRepository movieRepository;
  
      @Override
      public Flux&lt;Movie&gt; list(){
          return movieRepository.findAll();
      }
  }
  
  @RestController
  public class MovieRestController {
  
      @Autowired
      private MovieService movieService;
  
      @GetMapping(value = "/movies")
      public Flux&lt;Movie&gt; list() {
  
          return movieService.list();
      }
  }
  </code></pre>
  
  <p>2) When I Update an object I use a flatMap to update the object saved in Mongo, and then a Map to turn it to a Response Entity. My question is why am I using flatMap here instead of map? I derived this code from online examples, but no example explained the use of flatMap. I would like to understand why it is being used here. Below is the code.</p>
  
  <pre><code>@Service
  public class MovieServiceImpl implements MovieService {
  
      @Autowired
      private MovieRepository movieRepository;
  
      @Override
      public Mono&lt;Movie&gt; update(String id, MovieRequest movieRequest) {
  
         return movieRepository.findById(id).flatMap(existingMovie -&gt; {
  
             if(movieRequest.getDescription() != null){
                 existingMovie.setDescription(movieRequest.getDescription());
             }
             if(movieRequest.getRating() != null){
                 existingMovie.setRating(movieRequest.getRating());
             }
             if(movieRequest.getTitle() != null) {
                 existingMovie.setTitle(movieRequest.getTitle());
             }
  
             return movieRepository.save(existingMovie);
  
         });
      }
  }
  
  @RestController
  public class MovieRestController {
  
      @Autowired
      private MovieService movieService;
  
      @PutMapping("/movies/{movieId}")
      public Mono&lt;ResponseEntity&lt;Movie&gt;&gt; update(
              @PathVariable("movieId") final String movieId,
              @RequestBody final MovieRequest movieRequest) {
  
          return movieService.update(movieId, movieRequest)
                  .map(m -&gt; new ResponseEntity&lt;&gt;(m, HttpStatus.OK))
                  .defaultIfEmpty(new ResponseEntity&lt;&gt;(HttpStatus.NOT_FOUND));
  
      }
  }
  </code></pre>