我需要调用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
行?答案 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)
}
}
}