@@ -5,10 +5,6 @@ title: Atomic Cell
55
66A synchronized, concurrent, mutable reference.
77
8- Provides safe concurrent access and modification of its contents, by ensuring only one fiber
9- can operate on them at the time. Thus, all operations except ` get ` may semantically block the
10- calling fiber.
11-
128``` scala mdoc:silent
139abstract class AtomicCell [F [_], A ] {
1410 def get : F [A ]
@@ -20,34 +16,45 @@ abstract class AtomicCell[F[_], A] {
2016}
2117```
2218
19+ Provides safe concurrent access and modification of its contents, by ensuring only one fiber
20+ can operate on them at the time. Thus, all operations except ` get ` may semantically block the
21+ calling fiber.
22+
2323## Using ` AtomicCell `
2424
2525The ` AtomicCell ` can be treated as a combination of ` Mutex ` and ` Ref ` :
26+
2627``` scala mdoc:reset:silent
27- import cats .effect .{ IO , Ref }
28- import cats .effect .std .Mutex
28+ import cats .effect .IO
29+ import cats .effect .std .AtomicCell
2930
3031trait State
31- class Service (mtx : Mutex [IO ], ref : Ref [IO , State ]) {
32- def modify (f : State => IO [State ]): IO [Unit ] =
33- mtx.lock.surround {
34- for {
35- current <- ref.get
36- next <- f(current)
37- _ <- ref.set(next)
38- } yield ()
39- }
32+
33+ class Service (cell : AtomicCell [IO , State ]) {
34+ def modify (f : State => IO [State ]): IO [Unit ] =
35+ cell.evalUpdate(f)
4036}
4137```
4238
43- The following is the equivalent of the example above:
39+ ### Example
40+
41+ Imagine a random data generator,
42+ that requires running some effectual operations _ (e.g. checking a database)_
43+ to produce a new value.
44+ In that case, it may be better to block than to repeat the operation.
45+
4446``` scala mdoc:reset:silent
4547import cats .effect .IO
4648import cats .effect .std .AtomicCell
4749
48- trait State
49- class Service (cell : AtomicCell [IO , State ]) {
50- def modify (f : State => IO [State ]): IO [Unit ] =
51- cell.evalUpdate(current => f(current))
50+ trait Data
51+
52+ class RandomDataGenerator (cell : AtomicCell [IO , Data ]) {
53+ // Generates a new random value.
54+ def next : IO [Data ] =
55+ cell.evalUpdateAndGet(generate)
56+
57+ private def generate (previous : Data ): IO [Data ] =
58+ ???
5259}
5360```
0 commit comments