|
| 1 | +package org.learningconcurrency |
| 2 | +package exercises |
| 3 | +package ch6 |
| 4 | + |
| 5 | +/** |
| 6 | + Implement the reactive signal abstraction, represented with the Signal[T] type. |
| 7 | +
|
| 8 | + The Signal[T] type comes with the method apply, used to query the last event emitted by this signal, |
| 9 | + and several combinators with the same semantics as the corresponding Observable methods: |
| 10 | +
|
| 11 | + class Signal[T] { |
| 12 | + def apply(): T = ??? |
| 13 | + def map(f: T => S): Signal[S] = ??? |
| 14 | + def zip[S](that: Signal[S]): Signal[(T, S)] = ??? |
| 15 | + def scan[S](z: S)(f: (S, T) => S) = ??? |
| 16 | + } |
| 17 | +
|
| 18 | + Then, add the method toSignal to the Observable[T] type, which converts |
| 19 | + an Observable object to a reactive signal: def toSignal: Signal[T] = ??? |
| 20 | +
|
| 21 | + Consider using Rx subjects for this task. |
| 22 | + */ |
| 23 | + |
| 24 | +object Ex4 extends App { |
| 25 | + |
| 26 | + import rx.lang.scala._ |
| 27 | + |
| 28 | + implicit class ObserverableAdditional[T](val self:Observable[T]) extends AnyVal { |
| 29 | + |
| 30 | + def toSignal:Signal[T] = { |
| 31 | + val s = new Signal[T] |
| 32 | + self.last.subscribe(s.subject) |
| 33 | + s |
| 34 | + } |
| 35 | + |
| 36 | + } |
| 37 | + |
| 38 | + class Signal[T] { |
| 39 | + |
| 40 | + def this(t:T) { |
| 41 | + this() |
| 42 | + a = t |
| 43 | + } |
| 44 | + |
| 45 | + var a:T = _ |
| 46 | + |
| 47 | + val subject = Subject[T]() |
| 48 | + |
| 49 | + subject.subscribe(a = _) |
| 50 | + |
| 51 | + def apply(): T = a |
| 52 | + |
| 53 | + def map[S](f: T => S): Signal[S] = new Signal[S](f(a)) |
| 54 | + |
| 55 | + def zip[S](that: Signal[S]): Signal[(T, S)] = new Signal[(T,S)]((a,that.a)) |
| 56 | + |
| 57 | + def scan[S](z: S)(f: (S, T) => S):Signal[S] = new Signal[S](f(z,a)) |
| 58 | + } |
| 59 | + |
| 60 | + //test |
| 61 | + val s1 = Observable.items[String]("A","B","C").toSignal |
| 62 | + log(s"element = ${s1()}") |
| 63 | + |
| 64 | + val s2 = Observable.items[Int](1,2,3).toSignal |
| 65 | + |
| 66 | + val sMap = s1.map(_+"~") |
| 67 | + log(s"sMap: element = ${sMap()}") |
| 68 | + |
| 69 | + val sZip = s1.zip(s2) |
| 70 | + log(s"sZip: element = ${sZip()}") |
| 71 | + |
| 72 | + val sScan = s2.scan(10)((s,t)=>s+t) |
| 73 | + log(s"sScan: element = ${sScan()}") |
| 74 | + |
| 75 | + |
| 76 | + |
| 77 | +} |
0 commit comments