Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
  • Sep 05 2019 14:43
    @typelevel-bot banned @jdegoes
  • Jan 31 2019 21:17
    codecov-io commented #484
  • Jan 31 2019 21:08
    scala-steward opened #484
  • Jan 31 2019 18:19
    andywhite37 commented #189
  • Jan 31 2019 02:41
    kamilongus starred typelevel/cats-effect
  • Jan 30 2019 00:01
    codecov-io commented #483
  • Jan 29 2019 23:51
    deniszjukow opened #483
  • Jan 29 2019 23:37
  • Jan 29 2019 23:22
  • Jan 29 2019 20:26
    Rui-L starred typelevel/cats-effect
  • Jan 29 2019 18:01
    jdegoes commented #480
  • Jan 29 2019 17:04
    thomaav starred typelevel/cats-effect
  • Jan 28 2019 17:43
    asachdeva starred typelevel/cats-effect
  • Jan 28 2019 07:12
    alexandru commented #480
  • Jan 28 2019 05:45
    codecov-io commented #482
  • Jan 28 2019 05:35
    daron666 opened #482
  • Jan 27 2019 13:56
    codecov-io commented #481
  • Jan 27 2019 13:46
    lrodero opened #481
  • Jan 27 2019 05:47
    codecov-io commented #460
  • Jan 27 2019 05:37
    codecov-io commented #460
Marco Lopes
@mlopes
Ah ok, sorry, I'm migrating something from ce 2 to 3 and wasn't familiar with GenConcurrent. Thanks 🙂
David Gutsch
@gutscdav000
Hello All, I've been trying to get Meow-mtl working with cats-effect 3. I see that that could be a problem as I'm not sure the repo has been upgraded. Does anyone know of a workaround? I'm just trying to do some simple error handling kind of like this:
case class MyException(msg: String) extends Throwable

def handleOnlyMy[F[_], A](f: F[A], fallback: F[A])(implicit F: MonadError[F, MyException]) =
  f.handleErrorWith(_ => fallback)

val io: IO[Int] = ???
handleOnlyMy(io, 42)
Adam Rosien
@arosien
@gutscdav000 you may need MonadError[F, Throwable] instead
David Gutsch
@gutscdav000

Turned out to be some library versioning issues. This is the upgrade permutation that worked for me:

"org.typelevel" % "cats-mtl_2.13" % "1.0.0",
 "com.olegpy" % "meow-mtl-core_2.13" % "0.5.0",
//      "com.olegpy" % "meow-mtl-effects_2.13" % "0.5.0" // <-- error

note meow-mtl-effects was incompatible, but not required for my specific use of the library for error handling.
Thanks for the response @arosien !

B.Mady
@balanka
My project fails to compile after updating the dependencies ( cat from 2.6.1 to 2.7.0)
VatEndpoints.scala:19:24: parameter value evidence$2 in class VatEndpoints is never used [error] class VatEndpoints[F[_]: Sync, Auth: JWTMacAlgo] extends Http4sDsl[F] {
1 reply
Alexis Hernandez
@AlexITC

Hi everybody, I'm new to cats-effect and I'm trying to measure the execution time for a process, I wrote this but I'm not sure if this is the correct way to do it, I particularly wonder whether IO.delay could affect the measurement due to a potential context shift when computing start/end and when executing the actual input function:

  def trackExecutionTime[T](input: IO[T])(f: Long => IO[Unit]): IO[T] = {
    for {
      start  <- IO.delay(System.currentTimeMillis())
      result <- input
      end    <- IO.delay(System.currentTimeMillis())
      _      <- f(end - start)
    } yield result
  }

I understand that it would be ideal to replace the current time function by using a Clock instance but I believe it shouldn't matter for now.

Thanks.

Daniel Hinojosa
@dhinojosa
Ping @arosien. I think he has this in his book, maybe he can chime in. ☺️
Alexis Hernandez
@AlexITC
Thanks for the book reference
Daniel Hinojosa
@dhinojosa
Great book. He also has an IO debugger and a few other techniques
ritschwumm
@ritschwumm
@AlexITC looks correct to me. and yes, a Clock would be better. i'd probably at least use java.time.Instant.now instead of System.currentTimeMillis, if i went without a Clock.
if course it will not measure the duration of a failing input computation. depending on your needs, that's fine though.
Alexis Hernandez
@AlexITC

if course it will not measure the duration of a failing input computation. depending on your needs, that's fine though.

I'm aware, for this case I just care about successful outcomes

looks correct to me. and yes, a Clock would be better. i'd probably at least use java.time.Instant.now instead of System.currentTimeMillis, if i went without a Clock.

Thanks, I was worried about potential context-shifts affecting the measurement

Adam Rosien
@arosien
@AlexITC there is a slight amount of overhead, but it's ok. you can also use the Clock#timed method
Tomasz Bekas
@tbekas
Hi, is there a way to express via the type system in cats-effect that certain function is non-suspendable? I would like to prevent people from implementing the function that would call stuff like Temporal[F].sleep(1.second) and force them to schedule any suspendable action in the background or on a different fiber than the one that function was executed on.
Alexandr Oshlakov
@shadowsmind
Hello. Anyone have problem after update ce to new versions with messages like this?
"Non-daemon threads currently preventing JVM termination: - 107: Thread[search-backend-elastic-interaction-dispatcher-32,5,main]"
lekan
@horlahlekhon

Hello, am new to cats-effects and am confused about something

trait CampaignOpsResult {
  def message: String
}
case class CampaignOperationError(message: String) extends CampaignOpsResult
case class CampaignCreated(message: String = "Campaign Successfully created") extends CampaignOpsResult

val rr = for {
  db <- client
  coll <- db.getCollectionWithCodec[Campaign]("docs")
  existing: Option[Campaign] <- coll.find.filter(Filter.eq("campaignName", campaign.campaignName)).first
  writeResult: F[CampaignOpsResult] = if(existing.nonEmpty) CampaignOperationError("Campaign with that name exists before").pure
  else {
    for {
      res <- coll.insertOne(campaign)
      resp: CampaignOpsResult  = if(res.wasAcknowledged()) CampaignCreated() else CampaignOperationError("Unable to create campaign")
    } yield resp
  }
  res <- writeResult
} yield res

now i expect the writeResult variable to be a valid F[CampaignOpsResult] but everytime i tried get this error

  polymorphic expression cannot be instantiated to expected type;
  found   : [F[_]]F[CampaignOperationError]
  required: F[CampaignOpsResult]
  writeResult: F[CampaignOpsResult] = if(existing.nonEmpty) CampaignOperationError("Campaign with that name exists before").pure

Pls any advice is appreciated

Luis Miguel Mejía Suárez
@BalmungSan
@horlahlekhon this chat is mostly dead, you may want asking in the discord server instead: https://discord.gg/vgn8sEV3
Laurent Valdes
@valdo404
I guys, nice to know you
I would like to introspect an IO, so that I can have access to its execution graph
is it possible to do it ?
Or let's rephrase the intent maybe: I need a Show instance or an interpreter that let people see the contents of an IO instance.
Luis Miguel Mejía Suárez
@BalmungSan
@valdo404 you may have better luck in the discord server: https://discord.gg/JDQSt72z
ayeo
@ayeo
Hi all, I want to control the bulb using stream of signals. Each signal from the stream just toggle the bulb. I have no idea how to connect the pieces togheter. I have been trying to use for-comprehension but without any success. I have something like this at the moment.
  val signal1 =  Stream.repeatEval(producer("A", 100.millis))
  val signal2 =  Stream.repeatEval(producer("B", 200.millis))
  val signal: Stream[IO, String] = signal1.merge(signal2)

  class Bulb(ref: Ref[IO, Int]) {
    def toggle(): IO[Unit] = IO.println(("toggle")) >> IO.unit //todo
  }

  def pipes(bulb: Bulb): Pipe[IO, String, String] = in =>
    in.evalMap(signal => bulb.toggle() >> IO("Toggled"))


  val ioBulb: IO[Bulb] = for {
    r <- Ref[IO].of(0)
    b = new Bulb(r)
  } yield b
gvolpe
@gvolpe:matrix.org
[m]

ayeo (ayeo) assuming every toggle sets the internal Ref to either 1 or 0, you can do something like this.

object Main extends IOApp.Simple:
  val signal1 = Stream.emit[IO, String]("A").metered(100.millis)
  val signal2 = Stream.emit[IO, String]("B").metered(200.millis)

  def run: IO[Unit] = 
    Bulb.make[IO].flatMap { bulb =>
      signal1
        .merge(signal2)
        .evalMap(_ => IO.println("toggle") *> bulb.toggle)
        .interruptAfter(5.seconds)
        .compile
        .drain
    }

trait Bulb[F[_]]:
  def toggle: F[Unit]

object Bulb:
  def make[F[_]: Functor: Ref.Make]: F[Bulb[F]] =
    Ref[F].of(0).map { ref => 
      new:
        def toggle: F[Unit] = ref.update(x => if x == 0 then 1 else 0)
    }

Sleeps and timeouts don't work so well in the browser but you can see the compiling version here: https://scastie.scala-lang.org/NXdBGJLZTwyJeFh3tsgIwg

yanly007
@yanly007
Hello everyone,
Sorry if noob question, but I don't understand why using an instance of Async[F] where F is an effect monad, basically gives us access to the methods in MonadError too.
Async doesn't seem to extends MonadError...
Does Async have MonadError instances available regardless of what F is?
Luis Miguel Mejía Suárez
@BalmungSan
Hi @yanly007, first this channel is mostly dead, switch to discord.
Second, Async is a subtype of MonadError both in CE2 and in CE3.
yanly007
@yanly007
Thanks for the answer Luis!
CameronDiver
@CameronDiver
Hey, would anyone be able to help me understand some better ways to compose IO actions with cats?
Currently I've got something very akin to javascripts "callback hell", and there has to be a better way
I tried for example to use Either and map through assuming that the right bias will help, but it seems map keeps the value within the IO context
CameronDiver
@CameronDiver
basically any usage examples that have 3-4 io actions that depend on each being composed would be amazingly helpful
Luis Miguel Mejía Suárez
@BalmungSan
for? Or just plain flatMap?
CameronDiver
@CameronDiver
flatMap still propagates Either/Option etc though, so if I have something returning an IO[Either[A,B]], flatMap will pass Either[A,B] to the callback
so I've still got to do the standard unwrapping
let me show you the terrible code I've managed to cobble together
  def registerIntegration(req: Request[IO], auth: String) = {
    // First check that we have the correct payload
    req
      .as[RegisterIntegrationPayload]
      .option
      .flatMap({
        case None => BadRequest("Malformed request body")
        case Some(payload) => {
          // Check that the user referenced exists
          repository
            .getUser(payload.userId)
            .flatMap({
              case None => BadRequest("No user found")
              case Some(_) => {
                // Unwrap the lightning auth header
                authStringToLightningAuth(auth) match {
                  case Left(st) => BadRequest(st)
                  case Right((user, pass)) => {
                    // Make sure we have the correct authentication
                    LightningAdServer
                      .getAccount(user, pass)
                      .flatMap({
                        case Left(error) =>
                          InternalServerError(
                            s"Lightning ad server failed: $error"
                          )
                        case Right(accountName) => {
                          // Mark that the user is lightning registered
                          repository
                            .markUserLightningRegistered(payload.userId)
                            .flatMap(registered =>
                              if (registered)
                                Ok("Registered for lightning integration")
                              else
                                InternalServerError(
                                  "Failed to register for lightning integration"
                                )
                            )
                        }
                      })
                  }
                }
              }
            })
        }
      })
  }
it seems to me that I should be able to avoid this amount of identation in idiomatic scala/cats
but, I've no idea how :/
Luis Miguel Mejía Suárez
@BalmungSan
@CameronDiver So two things that may help.
Use EitherT or OptionT
(make sure to just use one, like convert all Eithers into Option or vice versa)
And then remember that foo.flatMap(x => x.bar.flatMap(y => ???)) is the same as foo.flatMap(x => x.bar).flatMap(y => ???)
i.e. you can always unnest flatMap calls.
The for syntax may help with that.
CameronDiver
@CameronDiver
The unnested flatMap calls is huge, I didn't notice that! I'll check out how to use EitherT/OptionT too. Really appreciate the help!
Naftoli Gugenheim
@nafg
You cannot always unnest flatMaps easily. For instance if y => ??? depended on x then to unnest you'd have to return a tuple to pass x along with the result of x.bar
tpetillot
@tpetillot
Hi folks! Would it be possible to convert A => F[B] to F[A => B]? I'm definitely missing something.
Naftoli Gugenheim
@nafg
@tpetillot try discord
tpetillot
@tpetillot
@nafg done, thanks!
antunonline
@antunonline
Hi guys, I'm playing with Cats Fibers and having hard time to find some information regarding the integration of Fibers and JVM NIO; specifically do Fibers block when calling NIO operations or are they somehow integrated with such calls and automatically poll/select on file/socket descriptors?