title: Mess with async function with two threads in Play app
body: <p>I am building a service method that suppose to build a CSV file. The titles of the file and results are coming from different threads. </p>
  
  <pre><code>def buildCsv(template: Template) : Future[TemporaryFile] = {
  
          val schemaFuture = dbViewSchemaRepository.findOneByTemplateId(template.id)
          val resultsFuture = checklistResultRepository.findAllByTemplateId(template.id)
  
          schemaFuture flatMap { optSchema =&gt;
              val schema = optSchema match {
                  case Some(sch : Schema) =&gt; sch
                  case _ =&gt; throw UnexpectedException("Schema not found")
              }
  
              //get the titles
              val titles = buildTitles(schema)
              // create temp file
              val tempFile = TemporaryFile("test", ".csv")
              logger.info("Absolute path: " + tempFile.file.getAbsolutePath)
  
              // start writing results
              resultsFuture map { results =&gt;
                  results foreach { result =&gt;
                      val resultRow = buildResultRow(result, schema)
  
                      tempFile.file.writeCsv(List(resultRow), ',', titles)
                  }
  
                  tempFile
              }
  
          }
      }
  </code></pre>
  
  <p>I've built a pretty simple test:</p>
  
  <pre><code>var dbViewSchemaRepo = mock[DbViewSchemaRepository]
              doReturn(Future(schema)).when(dbViewSchemaRepo).findOneByTemplateId(schema.templateId)
  
              var checklistResultRepo = mock[ChecklistResultRepository]
              doReturn(Future(List(result))).when(checklistResultRepo).findAllByTemplateId(schema.templateId)
  
              val template = mock[Template]
              template.id returns schema.templateId
  
              var srv = new ChecklistResultsExportService(dbViewSchemaRepo, checklistResultRepo)
  </code></pre>
  
  <p>When I run it I get an error:</p>
  
  <blockquote>
    <p>[error]    services.data.model.ChecklistSchema$Schema cannot be cast
    to scala.Option (ChecklistResultsExportService.scala:38) [error]
    services.data.ChecklistResultsExportService$$anonfun$buildCsv$1.apply(ChecklistResultsExportService.scala:38)</p>
  </blockquote>
  
  <p>Line 38 is this:</p>
  
  <pre><code>schemaFuture flatMap { optSchema
  </code></pre>
  
  <p>What am I missing?</p>
  
  <p>Thanks.</p>