Skip to content

Commit

Permalink
add evalMapFilter (ocadotechnology#204)
Browse files Browse the repository at this point in the history
  • Loading branch information
bwiercinski authored Jan 24, 2023
1 parent 9e5a1ed commit e04b8f2
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,13 @@ object Consumer extends ConsumerInstances {
def mapM[B](f: A => F[B])(implicit F: FlatMap[F]): Consumer[F, B] =
handler => self.consume(f >=> handler)

/** Allows to filter certain messages and execute an effect while doing it.
*
* For filtering without an effect use [[functorFilter]] instance.
*/
def evalMapFilter[B](f: A => F[Option[B]])(implicit F: Monad[F]): Consumer[F, B] =
Consumer.fromFunction[F, B](handler => self.consume(f(_).flatMap(_.fold(Applicative[F].unit)(handler))))

/** Similar to [[mapM()]], but discards the result of the tapped effect.
*/
def contraTapM(f: A => F[Unit])(implicit F: FlatMap[F]): Consumer[F, A] =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,25 @@ object ConsumerOpsTests extends SimpleMutableIOSuite with Checkers {
)
}

test("Consumer#evalMapFilter") {
for {
consumed <- Sender.testing[IO, Int]
ignored <- Sender.testing[IO, Int]
_ <- Consumer
.many[IO, Int](0 until 6: _*)
.evalMapFilter {
case i if i % 2 === 0 => IO.pure(Some(i))
case i => ignored.sendOne(i).as(None)
}
.forward(consumed)
consumedSent <- consumed.sent
ignoredSent <- ignored.sent
} yield assert.all(
consumedSent == List(0, 2, 4),
ignoredSent == List(1, 3, 5)
)
}

test("Consumer#surroundEachWith") {
for {
sender <- Sender.testing[IO, Int]
Expand Down

0 comments on commit e04b8f2

Please sign in to comment.