Add a sample for Source.unfoldResource #25468
This commit is contained in:
parent
023b379e3c
commit
7102c4744d
3 changed files with 153 additions and 4 deletions
|
|
@ -0,0 +1,56 @@
|
|||
/*
|
||||
* Copyright (C) 2009-2019 Lightbend Inc. <https://www.lightbend.com>
|
||||
*/
|
||||
|
||||
package docs.stream.operators.source
|
||||
|
||||
import akka.NotUsed
|
||||
import akka.actor.ActorSystem
|
||||
import akka.stream.scaladsl.Source
|
||||
|
||||
object UnfoldResource {
|
||||
|
||||
// imaginary blocking API we need to use
|
||||
// #unfoldResource-blocking-api
|
||||
trait Database {
|
||||
// blocking query
|
||||
def doQuery(): QueryResult
|
||||
}
|
||||
trait QueryResult {
|
||||
def hasMore: Boolean
|
||||
// potentially blocking retrieval of each element
|
||||
def nextEntry(): DatabaseEntry
|
||||
def close(): Unit
|
||||
}
|
||||
trait DatabaseEntry
|
||||
// #unfoldResource-blocking-api
|
||||
|
||||
def unfoldResourceExample(): Unit = {
|
||||
implicit val actorSystem = ActorSystem()
|
||||
// #unfoldResource
|
||||
// we don't actually have one, it was just made up for the sample
|
||||
val database: Database = ???
|
||||
|
||||
val queryResultSource: Source[DatabaseEntry, NotUsed] =
|
||||
Source.unfoldResource[DatabaseEntry, QueryResult](
|
||||
// open
|
||||
{ () =>
|
||||
database.doQuery()
|
||||
},
|
||||
// read
|
||||
{ query =>
|
||||
if (query.hasMore)
|
||||
Some(query.nextEntry())
|
||||
else
|
||||
// signals end of resource
|
||||
None
|
||||
},
|
||||
// close
|
||||
query => query.close())
|
||||
|
||||
// process each element
|
||||
queryResultSource.runForeach(println)
|
||||
// #unfoldResource
|
||||
}
|
||||
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue