-
Notifications
You must be signed in to change notification settings - Fork 596
/
Signal.scala
687 lines (580 loc) · 25.1 KB
/
Signal.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
/*
* Copyright (c) 2013 Functional Streams for Scala
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package fs2
package concurrent
import cats.kernel.Eq
import cats.effect.kernel.{Concurrent, Deferred, Ref, Resource}
import cats.effect.std.MapRef
import cats.effect.syntax.all._
import cats.syntax.all._
import cats.{Applicative, Functor, Invariant, Monad}
import scala.collection.immutable.LongMap
/** Pure holder of a single value of type `A` that can be read in the effect `F`. */
trait Signal[F[_], A] { outer =>
/** Returns a stream of the current value and subsequent updates to this signal.
*
* Even if you are pulling as fast as possible, updates that are very close together may
* result in only the last update appearing in the stream. In general, when you pull
* from this stream you may be notified of only the latest update since your last pull.
* If you want to be notified about every single update, use a `Queue` or `Channel` instead.
*/
def discrete: Stream[F, A]
/** Returns a stream of the current value of the signal. An element is always
* available -- on each pull, the current value is supplied.
*/
def continuous: Stream[F, A]
/** Gets the current value of this `Signal`.
*/
def get: F[A]
/** Returns the current value of this `Signal` and a `Stream` to subscribe to
* subsequent updates, with the same semantics as [[discrete]]. The updates
* stream should be compiled at most once.
*/
def getAndDiscreteUpdates(implicit F: Concurrent[F]): Resource[F, (A, Stream[F, A])] =
discrete.pull.uncons1
.flatMap(Pull.outputOption1(_))
.streamNoScope
.compile
.resource
.onlyOrError
/** Returns a signal derived from this one, that drops update events that did not change the value.
*/
def changes(implicit eqA: Eq[A]): Signal[F, A] =
new Signal[F, A] {
def discrete = outer.discrete.changes
def continuous = outer.continuous
def get = outer.get
override def getAndDiscreteUpdates(implicit F: Concurrent[F]) =
outer.getAndDiscreteUpdates.map { case (got, updates) =>
(got, updates.dropWhile(_ === got).changes)
}
}
/** Returns when the condition becomes true, semantically blocking
* in the meantime.
*
* This method is particularly useful to transform naive, recursive
* polling algorithms on the content of a `Signal`/ `SignallingRef`
* into semantically blocking ones. For example, here's how to
* encode a very simple cache with expiry, pay attention to the
* definition of `view`:
*
* {{{
* trait Refresh[F[_], A] {
* def get: F[A]
* }
* object Refresh {
* def create[F[_]: Temporal, A](
* action: F[A],
* refreshAfter: A => FiniteDuration,
* defaultExpiry: FiniteDuration
* ): Resource[F, Refresh[F, A]] =
* Resource
* .eval(SignallingRef[F, Option[Either[Throwable, A]]](None))
* .flatMap { state =>
* def refresh: F[Unit] =
* state.set(None) >> action.attempt.flatMap { res =>
* val t = res.map(refreshAfter).getOrElse(defaultExpiry)
* state.set(res.some) >> Temporal[F].sleep(t) >> refresh
* }
*
* def view = new Refresh[F, A] {
* def get: F[A] = state.get.flatMap {
* case Some(res) => Temporal[F].fromEither(res)
* case None => state.waitUntil(_.isDefined) >> get
* }
* }
*
* refresh.background.as(view)
* }
* }
* }}}
*
* Note that because `Signal` prioritizes the latest update when
* its state is updating very quickly, completion of the `F[Unit]`
* might not trigger if the condition becomes true and then false
* immediately after.
*
* Therefore, natural use cases of `waitUntil` tend to fall into
* two categories:
* - Scenarios where conditions don't change instantly, such as
* periodic timed processes updating the `Signal`/`SignallingRef`.
* - Scenarios where conditions might change instantly, but the `p`
* predicate is monotonic, i.e. if it tests true for an event, it
* will test true for the following events as well.
* Examples include waiting for a unique ID stored in a `Signal`
* to change, or waiting for the value of the `Signal` of an
* ordered `Stream[IO, Int]` to be greater than a certain number.
*/
def waitUntil(p: A => Boolean)(implicit F: Concurrent[F]): F[Unit] =
discrete.forall(a => !p(a)).compile.drain
}
object Signal extends SignalInstances {
def constant[F[_], A](a: A)(implicit F: Concurrent[F]): Signal[F, A] =
new Signal[F, A] {
def get: F[A] = F.pure(a)
def continuous: Stream[Pure, A] = Stream.constant(a)
override def getAndDiscreteUpdates(implicit
ev: Concurrent[F]
): Resource[F, (A, Stream[F, A])] =
Resource.pure((a, Stream.never(F)))
def discrete: Stream[F, A] = Stream(a) ++ Stream.never
}
def mapped[F[_]: Functor, A, B](fa: Signal[F, A])(f: A => B): Signal[F, B] =
new Signal[F, B] {
def continuous: Stream[F, B] = fa.continuous.map(f)
def discrete: Stream[F, B] = fa.discrete.map(f)
override def getAndDiscreteUpdates(implicit
ev: Concurrent[F]
): Resource[F, (B, Stream[F, B])] =
fa.getAndDiscreteUpdates(ev).map { case (a, updates) =>
(f(a), updates.map(f))
}
def get: F[B] = Functor[F].map(fa.get)(f)
}
implicit class SignalOps[F[_], A](val self: Signal[F, A]) extends AnyVal {
/** Converts this signal to signal of `B` by applying `f`.
*/
def map[B](f: A => B)(implicit F: Functor[F]): Signal[F, B] =
Signal.mapped(self)(f)
}
implicit class BooleanSignalOps[F[_]](val self: Signal[F, Boolean]) extends AnyVal {
/** Interrupts the supplied `Stream` when this `Signal` is `true`.
*/
def interrupt[A](s: Stream[F, A])(implicit F: Concurrent[F]): Stream[F, A] =
s.interruptWhen(self)
/** Predicates the supplied effect `f` on this `Signal` being `true`.
*/
def predicate[A](f: F[A])(implicit F: Monad[F]): F[Unit] =
self.get.flatMap(f.whenA)
}
}
/** Pure holder of a single value of type `A` that can be both read
* and updated in the effect `F`.
*
* The update methods have the same semantics as Ref, as well as
* propagating changes to `discrete` (with a last-update-wins policy
* in case of very fast updates).
*
* The `access` method differs slightly from `Ref` in that the update
* function, in the presence of `discrete`, can return `false` and
* need looping even without any other writers.
*/
abstract class SignallingRef[F[_], A] extends Ref[F, A] with Signal[F, A]
object SignallingRef {
private[fs2] final class PartiallyApplied[F[_]](
private val dummy: Boolean = true
) extends AnyVal {
/** @see [[SignallingRef.of]]
*/
def of[A](initial: A)(implicit F: Concurrent[F]): F[SignallingRef[F, A]] =
SignallingRef.of(initial)
}
/** Builds a `SignallingRef` value for data types that are `Concurrent`.
*
* This builder uses the
* [[https://typelevel.org/cats/guidelines.html#partially-applied-type-params Partially-Applied Type]]
* technique.
*
* {{{
* SignallingRef[IO].of(10L) <-> SignallingRef.of[IO, Long](10L)
* }}}
*
* @see [[of]]
*/
def apply[F[_]]: PartiallyApplied[F] = new PartiallyApplied[F]
/** Alias for `of`. */
def apply[F[_]: Concurrent, A](initial: A): F[SignallingRef[F, A]] =
of(initial)
/** Builds a `SignallingRef` for for effect `F`, initialized to the supplied value.
*/
def of[F[_], A](initial: A)(implicit F: Concurrent[F]): F[SignallingRef[F, A]] = {
case class State(
value: A,
lastUpdate: Long,
listeners: LongMap[Deferred[F, (A, Long)]]
)
F.ref(State(initial, 0L, LongMap.empty))
.product(F.ref(1L))
.map { case (state, ids) =>
def newId = ids.getAndUpdate(_ + 1)
def updateAndNotify[B](state: State, f: A => (A, B)): (State, F[B]) = {
val (newValue, result) = f(state.value)
val lastUpdate = state.lastUpdate + 1
val newState = State(newValue, lastUpdate, LongMap.empty)
val notifyListeners = state.listeners.values.toVector.traverse_ { listener =>
listener.complete(newValue -> lastUpdate)
}
newState -> notifyListeners.as(result)
}
new SignallingRef[F, A] {
def get: F[A] = state.get.map(_.value)
def continuous: Stream[F, A] = Stream.repeatEval(get)
def discrete: Stream[F, A] =
Stream.resource(getAndDiscreteUpdates).flatMap { case (a, updates) =>
Stream.emit(a) ++ updates
}
override def getAndDiscreteUpdates(implicit
ev: Concurrent[F]
): Resource[F, (A, Stream[F, A])] =
getAndDiscreteUpdatesImpl
private[this] def getAndDiscreteUpdatesImpl = {
def go(id: Long, lastSeen: Long): Stream[F, A] = {
def getNext: F[(A, Long)] =
F.deferred[(A, Long)]
.flatMap { wait =>
state.modify { case state @ State(value, lastUpdate, listeners) =>
if (lastUpdate != lastSeen)
state -> (value -> lastUpdate).pure[F]
else
state.copy(listeners = listeners + (id -> wait)) -> wait.get
}
}
.flatten // cancelable
Stream.eval(getNext).flatMap { case (a, lastUpdate) =>
Stream.emit(a) ++ go(id, lastSeen = lastUpdate)
}
}
def cleanup(id: Long): F[Unit] =
state.update(s => s.copy(listeners = s.listeners - id))
Resource.eval(state.get.map { s =>
(s.value, Stream.bracket(newId)(cleanup).flatMap(go(_, s.lastUpdate)))
})
}
def set(a: A): F[Unit] = update(_ => a)
def update(f: A => A): F[Unit] = modify(a => (f(a), ()))
def modify[B](f: A => (A, B)): F[B] =
state.flatModify(updateAndNotify(_, f))
def tryModify[B](f: A => (A, B)): F[Option[B]] =
state.tryModify(updateAndNotify(_, f)).flatMap(_.sequence).uncancelable
def tryUpdate(f: A => A): F[Boolean] =
tryModify(a => (f(a), ())).map(_.isDefined)
def access: F[(A, A => F[Boolean])] =
state.access.map { case (state, set) =>
val setter = { (newValue: A) =>
val (newState, notifyListeners) =
updateAndNotify(state, _ => (newValue, ()))
set(newState).flatTap { succeeded =>
notifyListeners.whenA(succeeded)
}
}
(state.value, setter)
}
def tryModifyState[B](state: cats.data.State[A, B]): F[Option[B]] = {
val f = state.runF.value
tryModify(a => f(a).value)
}
def modifyState[B](state: cats.data.State[A, B]): F[B] = {
val f = state.runF.value
modify(a => f(a).value)
}
}
}
}
/** Creates an instance focused on a component of another SignallingRef's value. Delegates every get and
* modification to underlying SignallingRef, so both instances are always in sync.
*/
def lens[F[_], A, B](
ref: SignallingRef[F, A]
)(get: A => B, set: A => B => A)(implicit F: Functor[F]): SignallingRef[F, B] =
new LensSignallingRef(ref)(get, set)
private final class LensSignallingRef[F[_], A, B](underlying: SignallingRef[F, A])(
lensGet: A => B,
lensSet: A => B => A
)(implicit F: Functor[F])
extends SignallingRef[F, B] {
def discrete: Stream[F, B] = underlying.discrete.map(lensGet)
def continuous: Stream[F, B] = underlying.continuous.map(lensGet)
def get: F[B] = F.map(underlying.get)(a => lensGet(a))
override def getAndDiscreteUpdates(implicit ev: Concurrent[F]): Resource[F, (B, Stream[F, B])] =
underlying.getAndDiscreteUpdates.map { case (a, updates) =>
(lensGet(a), updates.map(lensGet))
}
def set(b: B): F[Unit] = underlying.update(a => lensModify(a)(_ => b))
override def getAndSet(b: B): F[B] =
underlying.modify(a => (lensModify(a)(_ => b), lensGet(a)))
def update(f: B => B): F[Unit] =
underlying.update(a => lensModify(a)(f))
def modify[C](f: B => (B, C)): F[C] =
underlying.modify { a =>
val oldB = lensGet(a)
val (b, c) = f(oldB)
(lensSet(a)(b), c)
}
def tryUpdate(f: B => B): F[Boolean] =
F.map(tryModify(a => (f(a), ())))(_.isDefined)
def tryModify[C](f: B => (B, C)): F[Option[C]] =
underlying.tryModify { a =>
val oldB = lensGet(a)
val (b, result) = f(oldB)
(lensSet(a)(b), result)
}
def tryModifyState[C](state: cats.data.State[B, C]): F[Option[C]] = {
val f = state.runF.value
tryModify(a => f(a).value)
}
def modifyState[C](state: cats.data.State[B, C]): F[C] = {
val f = state.runF.value
modify(a => f(a).value)
}
val access: F[(B, B => F[Boolean])] =
F.map(underlying.access) { case (a, update) =>
(lensGet(a), b => update(lensSet(a)(b)))
}
private def lensModify(s: A)(f: B => B): A = lensSet(s)(f(lensGet(s)))
}
implicit def invariantInstance[F[_]: Functor]: Invariant[SignallingRef[F, *]] =
new Invariant[SignallingRef[F, *]] {
override def imap[A, B](fa: SignallingRef[F, A])(f: A => B)(g: B => A): SignallingRef[F, B] =
new SignallingRef[F, B] {
def get: F[B] = fa.get.map(f)
def discrete: Stream[F, B] = fa.discrete.map(f)
def continuous: Stream[F, B] = fa.continuous.map(f)
override def getAndDiscreteUpdates(implicit
ev: Concurrent[F]
): Resource[F, (B, Stream[F, B])] =
fa.getAndDiscreteUpdates(ev).map { case (a, updates) =>
(f(a), updates.map(f))
}
def set(b: B): F[Unit] = fa.set(g(b))
def access: F[(B, B => F[Boolean])] =
fa.access.map { case (getter, setter) =>
(f(getter), b => setter(g(b)))
}
def tryUpdate(h: B => B): F[Boolean] = fa.tryUpdate(a => g(h(f(a))))
def tryModify[B2](h: B => (B, B2)): F[Option[B2]] =
fa.tryModify(a => h(f(a)).leftMap(g))
def update(bb: B => B): F[Unit] =
modify(b => (bb(b), ()))
def modify[B2](bb: B => (B, B2)): F[B2] =
fa.modify { a =>
val (a2, b2) = bb(f(a))
g(a2) -> b2
}
def tryModifyState[C](state: cats.data.State[B, C]): F[Option[C]] =
fa.tryModifyState(state.dimap(f)(g))
def modifyState[C](state: cats.data.State[B, C]): F[C] =
fa.modifyState(state.dimap(f)(g))
}
}
}
/** A [[MapRef]] with a [[SignallingRef]] for each key. */
trait SignallingMapRef[F[_], K, V] extends MapRef[F, K, V] {
override def apply(k: K): SignallingRef[F, V]
}
object SignallingMapRef {
/** Builds a `SignallingMapRef` for effect `F`, initialized to the supplied value.
*
* Update semantics for `discrete` are the same as `SignallingRef`, with one exception:
* it cannot distinguish updates that remove a key (by setting its value to `None`).
*
* More specifically: if you remove a key, this will only notify once per listener
* i.e. setting it to `None` again will not trigger another update.
* Furthermore, if a listener's last pull returned `None`, and by the time it pulls again the
* current value is `None`, then it will not be notified regardless of any non-`None` updates
* that may have happened between the pulls. This special semantic for `None` is necessary to
* prevent memory leaks at keys with no values and no listeners.
*/
def ofSingleImmutableMap[F[_], K, V](
initial: Map[K, V] = Map.empty[K, V]
)(implicit F: Concurrent[F]): F[SignallingMapRef[F, K, Option[V]]] = {
case class State(
lastUpdate: Long,
keys: Map[K, KeyState]
)
type Listener = Deferred[F, (Option[V], Long)]
// fix lastUpdate at -1 when the value is not present
// so we don't have to keep an update counter when the key has neither a value nor any listeners
case class KeyState(
value: Option[V],
lastUpdate: Long,
listeners: LongMap[Listener]
)
F.ref(State(0L, initial.map { case (k, v) => k -> KeyState(Some(v), 0L, LongMap.empty) }))
.product(F.ref(1L))
.map { case (state, ids) =>
def newId = ids.getAndUpdate(_ + 1)
def updateAndNotify[U](state: State, k: K, f: Option[V] => (Option[V], U))
: (State, F[U]) = {
val keyState = state.keys.get(k)
val (newValue, result) = f(keyState.flatMap(_.value))
val lastUpdate = {
val lu = state.lastUpdate + 1
// skip -1 b/c of its special semantic
if (lu == -1L) 0L else lu
}
val lastKeyUpdate = if (newValue.isDefined) lastUpdate else -1L
val newKeys =
if (newValue.isDefined)
state.keys.updated(k, KeyState(newValue, lastKeyUpdate, LongMap.empty))
else
state.keys - k // prevent memory leak
val newState = State(lastUpdate, newKeys)
val notifyListeners = keyState.fold(F.unit) { keyState =>
keyState.listeners.values.toVector.traverse_ { listener =>
listener.complete(newValue -> lastKeyUpdate)
}
}
newState -> notifyListeners.as(result)
}
k =>
new SignallingRef[F, Option[V]] {
def get: F[Option[V]] = state.get.map(_.keys.get(k).flatMap(_.value))
def continuous: Stream[F, Option[V]] = Stream.repeatEval(get)
def discrete: Stream[F, Option[V]] =
Stream.resource(getAndDiscreteUpdates).flatMap { case (a, updates) =>
Stream.emit(a) ++ updates
}
override def getAndDiscreteUpdates(implicit
ev: Concurrent[F]
): Resource[F, (Option[V], Stream[F, Option[V]])] =
getAndDiscreteUpdatesImpl
private[this] def getAndDiscreteUpdatesImpl = {
def go(id: Long, lastSeen: Long): Stream[F, Option[V]] = {
def getNext: F[(Option[V], Long)] =
F.deferred[(Option[V], Long)]
.flatMap { wait =>
state.modify { state =>
val keyState = state.keys.get(k)
val value = keyState.flatMap(_.value)
val lastUpdate = keyState.fold(-1L)(_.lastUpdate)
val listeners = keyState.fold(LongMap.empty[Listener])(_.listeners)
if (lastUpdate != lastSeen)
state -> (value -> lastUpdate).pure[F]
else {
val newKeys =
state.keys
.updated(k, KeyState(value, lastUpdate, listeners.updated(id, wait)))
state.copy(keys = newKeys) -> wait.get
}
}
}
.flatten // cancelable
Stream.eval(getNext).flatMap { case (v, lastUpdate) =>
Stream.emit(v) ++ go(id, lastSeen = lastUpdate)
}
}
def cleanup(id: Long): F[Unit] =
state.update { state =>
state.keys.get(k).fold(state) { case KeyState(value, lastUpdate, listeners) =>
val newListeners = listeners - id
val newKeys =
if (value.isEmpty && newListeners.isEmpty)
state.keys - k // prevent memory leak
else
state.keys.updated(k, KeyState(value, lastUpdate, newListeners))
state.copy(keys = newKeys)
}
}
Resource.eval(state.get.map { state =>
(
state.keys.get(k).flatMap(_.value),
Stream
.bracket(newId)(cleanup)
.flatMap(go(_, state.keys.get(k).fold(-1L)(_.lastUpdate)))
)
})
}
def set(v: Option[V]): F[Unit] = update(_ => v)
def update(f: Option[V] => Option[V]): F[Unit] = modify(v => (f(v), ()))
def modify[U](f: Option[V] => (Option[V], U)): F[U] =
state.flatModify(updateAndNotify(_, k, f))
def tryModify[U](f: Option[V] => (Option[V], U)): F[Option[U]] =
state.tryModify(updateAndNotify(_, k, f)).flatMap(_.sequence).uncancelable
def tryUpdate(f: Option[V] => Option[V]): F[Boolean] =
tryModify(a => (f(a), ())).map(_.isDefined)
def access: F[(Option[V], Option[V] => F[Boolean])] =
state.access.map { case (state, set) =>
val setter = { (newValue: Option[V]) =>
val (newState, notifyListeners) =
updateAndNotify(state, k, _ => (newValue, ()))
set(newState).flatTap { succeeded =>
notifyListeners.whenA(succeeded)
}
}
(state.keys.get(k).flatMap(_.value), setter)
}
def tryModifyState[U](state: cats.data.State[Option[V], U]): F[Option[U]] = {
val f = state.runF.value
tryModify(v => f(v).value)
}
def modifyState[U](state: cats.data.State[Option[V], U]): F[U] = {
val f = state.runF.value
modify(v => f(v).value)
}
}
}
}
}
private[concurrent] trait SignalInstances extends SignalLowPriorityInstances {
implicit def applicativeInstance[F[_]: Concurrent]: Applicative[Signal[F, *]] = {
def nondeterministicZip[A0, A1](
x0: A0,
xs: Stream[F, A0],
y0: A1,
ys: Stream[F, A1]
): Stream[F, (A0, A1)] =
xs.either(ys)
.scan((x0, y0)) {
case ((_, rightElem), Left(newElem)) => (newElem, rightElem)
case ((leftElem, _), Right(newElem)) => (leftElem, newElem)
}
.drop(1)
new Applicative[Signal[F, *]] {
override def map[A, B](fa: Signal[F, A])(f: A => B): Signal[F, B] = Signal.mapped(fa)(f)
def pure[A](x: A): Signal[F, A] = Signal.constant(x)
def ap[A, B](ff: Signal[F, A => B])(fa: Signal[F, A]): Signal[F, B] =
new Signal[F, B] {
def discrete: Stream[F, B] =
Stream.resource(getAndDiscreteUpdates).flatMap { case (a, updates) =>
Stream.emit(a) ++ updates
}
def continuous: Stream[F, B] = Stream.repeatEval(get)
def get: F[B] = ff.get.ap(fa.get)
override def getAndDiscreteUpdates(implicit
ev: Concurrent[F]
): Resource[F, (B, Stream[F, B])] = getAndDiscreteUpdatesImpl
private[this] def getAndDiscreteUpdatesImpl =
(ff.getAndDiscreteUpdates, fa.getAndDiscreteUpdates).mapN { case ((f, fs), (a, as)) =>
(f(a), nondeterministicZip(f, fs, a, as).map { case (f, a) => f(a) })
}
}
}
}
}
private[concurrent] trait SignalLowPriorityInstances {
/** Note that this is not subsumed by [[Signal.applicativeInstance]] because
* [[Signal.applicativeInstance]] requires a `Concurrent[F]`
* since it non-deterministically zips elements together while our
* `Functor` instance has no other constraints.
*
* Separating the two instances allows us to make the `Functor` instance
* more general.
*
* We put this in a `SignalLowPriorityImplicits` trait to resolve ambiguous
* implicits if the [[Signal.applicativeInstance]] is applicable, allowing
* the `Applicative` instance to be chosen.
*/
implicit def functorInstance[F[_]: Functor]: Functor[Signal[F, *]] =
new Functor[Signal[F, *]] {
def map[A, B](fa: Signal[F, A])(f: A => B): Signal[F, B] =
Signal.mapped(fa)(f)
}
}