如何将结果组合成多个来源的流

时间:2017-06-06 11:22:01

标签: scala slick reactive-streams

我使用slick-3.0.0并尝试使用streaming

假设有AccountsTablePreferencesTable

我想从PreferencesTable获取一些信息并将其用于AccountsTable的流。例如(见TODO):

val somePrefQuery: Query[Rep[String], ...] = PreferencesTable.filter(...)
val somePrefAction = somePrefQuery.result
val somePrefStream = db.stream(somePrefAction)

val accountsStream: DatabasePublisher[String] = 
                              db.stream(AccountsTable.map(_.id).result)

accountsStream.mapResult { accountId: String =>
   //TODO how to get somePref value from 
   //     somePrefQuery or somePrefAction or somePrefStream
   // Is there best approach for such task?
   val somePref: String = ???

   val result:(String, String) = (accountId, somePref)
   result
}

1 个答案:

答案 0 :(得分:1)

Akka提供concurrent streaming functionality,允许您以您描述的方式组合流。

您首先要创建accountId值的来源:

import akka.stream.scaladsl.Source

val accountIdSrc : Source[String, _] = 
  Source fromPublisher (db stream (AccountsTable.map(_.id).result))

然后可以将此Source附加到pref查询逻辑:

def queryForPrefs(accountId : String) =
  PreferenceTable
    .filter(_.accountId === accountId)
    .map(_.pref)
    .result

case class PrefData(accountId : String, somePref : String)

val accountAndPrefSrc : Source[PrefData, _] = 
  accountIdSrc flatMapConcat { accountId =>
    Source
      .fromPublisher(db stream queryForPrefs(accountId))
      .map(pref => PrefData(accountId, pref))
  }