fs2 icon indicating copy to clipboard operation
fs2 copied to clipboard

parEvalMap* runs resource finaliser before usage

Open nikiforo opened this issue 3 years ago • 4 comments

Found by: @lavrov Original message

Example:

//> using lib "co.fs2::fs2-core::3.2.4"

import cats.effect.*
import fs2.*
import scala.concurrent.duration.*

object Main extends IOApp.Simple:

  def run =
    Stream
      .resource(Resource.make(IO.println("acquire"))(_ => IO.println("release")))
      .parEvalMap(2)(id =>
        IO.sleep(1.second) >> IO.println("use")
      )
      .compile
      .drain

Expected logs:

acquire
use
release

Actual logs:

acquire
release
use

nikiforo avatar Dec 06 '22 14:12 nikiforo

@diesalbla identified the issue to here: https://github.com/typelevel/fs2/blob/57032ffdc4906b54a0f1acf4b506a2c5b97f9084/core/shared/src/main/scala/fs2/Stream.scala#L2201

The problem is if the background stream (which is derived from the resource-acquiring stream) completes before the foreground stream then it will release the resources.

I am not sure if there is concurrently-like solution, but I was imagining we could do something like:

Stream.resource(background.compile.resource.something).flatMap { _ =>
  foreground ...
}

The precise details are a bit fuzzy :)

armanbilge avatar Dec 06 '22 17:12 armanbilge

@armanbilge If possible, I would like to work on this issue.

tothpeti avatar Sep 13 '23 06:09 tothpeti

Unfortunately, I haven't been able to make any noticable progression with the ticket since I picked it up. This is why I will unassign myself from it.

tothpeti avatar Dec 26 '23 09:12 tothpeti