cats-effect
cats-effect copied to clipboard
Document that Fibers can close over non-volatile vars
trafficstars
a fiber can close over a non volatile var safely we should add it to the docs because it's come up a few times
:point_up:
The (hacky, non-FP) example I used to ask about this:
def actorThatOnlyUpdatesState[F[_]: Async, S](
initialState: F[S]
) = for {
inbox <- Queue.unbounded[F, S => S]
s <- initialState
_ <- {
var state = s
inbox.take.map(f => state = f(state)).foreverM
}.start
} yield inbox.offer _
This loops over a Queue that contains S => S, which updates the state. I can then push S => S functions onto that queue, which will then be executed. Apparently the state = f(state) is not an issue here from a thread-safety perspective.
Yep, I remember finding out about this via word-of-mouth 😆