-
Notifications
You must be signed in to change notification settings - Fork 39
/
Forwardable.scala
73 lines (63 loc) · 2.34 KB
/
Forwardable.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
package reactive
/**
* This typeclass witness the ability of a target
* to have values forwarded to it.
*/
trait CanForwardTo[-Target, Value] {
def forwarder(t: Target): Value => Unit
}
object CanForwardTo {
implicit def vari[T]: CanForwardTo[Var[T], T] = new CanForwardTo[Var[T], T] {
def forwarder(t: Var[T]) = NamedFunction(">>"+t.debugName)(t.update)
}
implicit def eventSource[T]: CanForwardTo[EventSource[T], T] = new CanForwardTo[EventSource[T], T] {
def forwarder(t: EventSource[T]) = NamedFunction(">>"+t.debugString)(t.fire)
}
}
trait Foreachable[+A] {
def foreach(f: A => Unit)(implicit observing: Observing): Unit
}
/**
* Something from which values can be forwarded
*/
trait Forwardable[+T, +Self] extends Any {
def self: Self
def foreach(thunk: T => Unit)(implicit observing: Observing): Self
/**
* Forwards values from this Forwardable to a target, for whose type a CanForwardTo exists (in the implicit scope).
* @return the forwarding instance
*/
def >>[U >: T, S](target: S)(implicit canForwardTo: CanForwardTo[S, U], observing: Observing): Self =
this foreach canForwardTo.forwarder(target)
/**
* Forwards values from this Forwardable to a target, for whose type a CanForwardTo exists (in the implicit scope).
* This operator is available for right associativity. For example:
* val time = Var(0) <<: timerTicks // equivalent to: val time = Var(0); timerTicks >> time
*
* @return the target
*/
def <<:[U >: T, S](target: S)(implicit canForwardTo: CanForwardTo[S, U], observing: Observing): S = {
this foreach canForwardTo.forwarder(target)
target
}
/**
* Apply a function for every value
*/
def =>>(thunk: T => Unit)(implicit observing: Observing): Self =
this foreach NamedFunction("=>>"+thunk)(thunk)
/**
* Apply a function for every value. Same as =>>.
*/
def +=(thunk: T => Unit)(implicit observing: Observing): Self =
this foreach NamedFunction("+="+thunk)(thunk)
/**
* Apply a PartialFunction for every applicable value
*/
def ?>>(pf: PartialFunction[T, Unit])(implicit observing: Observing): Self =
this foreach NamedFunction("?>>"+pf)(pf orElse { case _ => })
/**
* Run a block of code for every value
*/
def ->>(block: => Unit)(implicit observing: Observing): Self =
this.foreach(NamedFunction[T, Unit]("->>{...}")(_ => block))
}