background
puts the entire implementation on another thread (is fiber a better word here?)? Also, Daniel inadvertently (I think) switched f and sleep so it's not quite the same? Just checking my understanding.
background
is just a different combinator that uses Resource
to manage start
(i.e. a Fiber)
background
abstracts for you
start
and then immediately join
IO.shift
sleep
already does it under the hood
handleErrorWith
there
Also, Daniel inadvertently (I think) switched f and sleep so it's not quite the same? J
yeah I think so
scala> (IO.raiseError(new Exception()) >> IO(println("foo"))).unsafeRunSync()
java.lang.Exception
... 11 elided
f.attempt <*
and no handleError
at the end
background
gives you an F[A] as the resource, which in the example is just thrown away. I was conducting a thought experiment where startUpdate would actually create the Ref and return it, but then I ended up with Resource[IO, IO[Ref[IO,A]]]
so I need to flatMap
on the value which I've gotten as the resource (which seems weird). Are there some examples where the value coming out of the IO that's being run by background is actually used?
//Update r every duration by running f.
def startUpdate[A](f: IO[A], duration: FiniteDuration): IO[Ref[IO, A]] = {
def loop(r: Ref[IO, A]): IO[Unit] = {
for {
_ <- IO.sleep(duration)
newValue <- f
_ <- r.set(newValue)
} yield ()
}.attempt >> loop(r)
for {
initial <- f
ref <- Ref.of[IO, A](initial)
_ <- loop(ref)
} yield ref
}
fs2.hold
basically
although
Stream.repeatEval(f).metered(duration).hold(initial).compile.resource
should do the whole thing for you
Resource[F, Signal[F, A]]
rather then Ref
, but they both have .get: F[A]
background
basically means "spawns this fiber, but keep track of canceling if I get canceled for me"
F[A]
that it returns you if the join
on the fiber you have spawned
hold
)
trait Fiber[F[_], A] {
def join: F[A] // wait for this fiber to complete, give me result
def cancel: F[Unit] // cancel and wait for the fiber to finalise
}
def start(fa: F[A]): F[Fiber[F, A]] // start a fiber with `fa`, and give a handle to wait for it or cancel it
start
directly, you risk leaking a fiber (and the process you have spawned within it
start >> doSomething
or start.flatMap { doSomething with fiber
timeout
), the fiber you have spawned would just keep going in the background