问题
I have an IO Source I'm multiplexing a file and handing off to another part of the system to execute like:
source.alsoTo(FileIO.toPath(path))
This is used for a cache, i.e. i'm writing a file passing through my system to a temporary cache location. Once the cache is written, I want to move it atomically to its final location.
The consumer of the source gets a Future
and knows when it is done, but my side-channel writing to file to disk has no such facility that I can find. Is there some way of attaching a completion handler to a sink so that I can complete my manipulation of that file?
回答1:
Instead of alsoTo
, use alsoToMat
and mapMaterializedValue
to access the materialized value of the file Sink
:
val source: Source[ByteString, _] = ???
val cachedSource =
source
.alsoToMat(FileIO.toPath(path))(Keep.right)
.mapMaterializedValue { fileResult => // fileResult is a Future[IOResult]
// do something with fileResult
}
来源:https://stackoverflow.com/questions/53437098/triggering-on-fileio-topath-sink-completion