Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Added debug and debugChunks combinators #1727

Merged
merged 4 commits into from
Jan 7, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions core/shared/src/main/scala/fs2/Stream.scala
Original file line number Diff line number Diff line change
Expand Up @@ -656,6 +656,59 @@ final class Stream[+F[_], +O] private (private[fs2] val free: FreeC[F, O, Unit])
def metered[F2[x] >: F[x]: Timer](rate: FiniteDuration): Stream[F2, O] =
Stream.fixedRate[F2](rate).zipRight(this)

/**
* Logs the elements of this stream as they are pulled.
*
* By default, `toString` is called on each element and the result is printed
* to standard out. To change formatting, supply a value for the `formatter`
* param. To change the destination, supply a value for the `logger` param.
*
* This method does not change the chunk structure of the stream. To debug the
* chunk structure, see [[debugChunks]].
*
* Logging is not done in `F` because this operation is intended for debugging,
* including pure streams.
*
* @example {{{
* scala> Stream(1, 2).append(Stream(3, 4)).debug(o => s"a: $o").toList
* a: 1
* a: 2
* a: 3
* a: 4
* res0: List[Int] = List(1, 2, 3, 4)
* }}}
*/
def debug(
formatter: O => String = _.toString,
logger: String => Unit = println(_)
): Stream[F, O] =
map { o =>
logger(formatter(o))
o
}

/**
* Like [[debug]] but logs chunks as they are pulled instead of individual elements.
*
* @example {{{
* scala> Stream(1, 2, 3).append(Stream(4, 5, 6)).debugChunks(c => s"a: $c").buffer(2).debugChunks(c => s"b: $c").toList
* a: Chunk(1, 2, 3)
* b: Chunk(1, 2)
* a: Chunk(4, 5, 6)
* b: Chunk(3, 4)
* b: Chunk(5, 6)
* res0: List[Int] = List(1, 2, 3, 4, 5, 6)
* }}}
*/
def debugChunks(
formatter: Chunk[O] => String = _.toString,
logger: String => Unit = println(_)
): Stream[F, O] =
chunks.flatMap { os =>
logger(formatter(os))
Stream.chunk(os)
}

/**
* Returns a stream that when run, sleeps for duration `d` and then pulls from this stream.
*
Expand Down