Skip to content

Commit

Permalink
make ReadStateChannel into a monad
Browse files Browse the repository at this point in the history
  • Loading branch information
fabianschmitthenner committed Apr 26, 2016
1 parent 6635617 commit faadfbe
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
8 changes: 8 additions & 0 deletions shared/src/main/scala/pl/metastack/metarx/Channel.scala
Original file line number Diff line number Diff line change
Expand Up @@ -736,6 +736,14 @@ trait RootChannel[T]

trait ReadStateChannel[T] extends ReadChannel[T] {
def get: T

def flatMap[U](f: T => ReadStateChannel[U]): ReadStateChannel[U] = {
flatMap(f.asInstanceOf[T => ReadChannel[U]]).cache(f(get).get)
}

override def map[U](f: T => U): ReadStateChannel[U] = {
flatMap { x => Var(f(x)) }
}
}

/** In Rx terms, a [[StateChannel]] can be considered a cold observable. */
Expand Down
13 changes: 12 additions & 1 deletion shared/src/test/scala/pl/metastack/metarx/ChannelTest.scala
Original file line number Diff line number Diff line change
Expand Up @@ -480,12 +480,23 @@ class ChannelTest extends CompatTest {
test("flatMap() (3)") {
var value = ""
Var(42)
.flatMap(x => Var(x.toString))
.flatMap((x: Int) => Var(x.toString))
.filter(_ => true)
.attach(value = _)
assertEquals(value, "42")
}

test("flatMap() (4)") {
val v1 = Var(42)
val v2 = v1.map((x: Int) => x + 1)
var resultList: List[Int] = List.empty
v2.attach{ x => resultList = resultList ++ List(x) }
assertEquals (v2.get, 43)
v1.update(_ => 43)
assertEquals(v2.get, 44)
assertEquals(resultList, List(43, 44))
}

test("flatMapCh()") {
val ch = Channel[Var[Int]]()
val a = ch.flatMapCh(cur => cur)
Expand Down

0 comments on commit faadfbe

Please sign in to comment.