如何首先从一个流中获取然后传递给另一流

时间:2019-02-26 16:30:42

标签: scala akka akka-stream

我需要调用cassandra来获取日期,然后将获取的日期传递给另一个将数据插入数据库的流。

def fetchDate: Future[Done] =
  readJournal(persistenceKey)
    .drop(3)
    .take(1)
    .map(l => l.mydate)
    .runWith(Sink.ignore)

def insertRowsToDb: Future[Done] = 
  readJournal(somePersistenceKey)
    .drop(4)
    .take(1)
    .map(data => MyClass(data))
    .mapAsync(1) { myData => 
      for {
        insert <- myRepository.insert(data.id, fetchDate) //error here because fetchDate is unavailable 
      }
    }

  class MyRepository(tableName: String) {
    def insert(id: String, fetchedDate: Long): Future[Int] =
      config.db.run {
        sqlu"""INSERT INTO #${tableName}
           VALUES (
            ${id},
            ${fetchedDate}
           )
          """
      }

问题

  • 如何首先执行fetchDate,然后将其结果传递到myRepository.insert行?

1 个答案:

答案 0 :(得分:0)

您有两个问题。首先是fetchDate甚至没有保留日期!要解决此问题,就意味着要运行Sink,而不仅仅是执行“忽略”操作:

def fetchDateFut: Future[Date] =
  readJournal(persistenceKey)
    .drop(3)
    .take(1)
    .map(l => l.mydate)
    .runWith(Sink.last)

然后,您需要flatMap Future才能使该日期生效:

def insertRowsToDb: Future[Done] = fetchDateFut.flatMap { fetchDate: Date =>
  readJournal(somePersistenceKey)
    .drop(4)
    .take(1)
    .map(data => MyClass(data))
    .mapAsync(1) { myData => 
      for {
        insert <- myRepository.insert(data.id, fetchDate)
      }
    }
}