Created
March 11, 2016 20:08
-
-
Save seamusv/ee388cd5d8f59502f922 to your computer and use it in GitHub Desktop.
Using Rx to update the configuration stream. No variables to hold the state.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.cosa | |
import rx.lang.scala.subjects.{BehaviorSubject, PublishSubject} | |
object ConfigurationExample1 extends App { | |
val poleSubject = PublishSubject[String]() | |
val configurations = BehaviorSubject(Map.empty[Pole, Config]) | |
configurations.subscribe(x => println("Configurations: " + x)) | |
poleSubject | |
.map({ | |
case x if x.startsWith("L") => Config(LeftPole, "Lefty! " + x) | |
case x => Config(RightPole, "Poling to the right... " + x) | |
}) | |
.withLatestFrom(configurations) { case (config, configMap) => | |
println("Receiving configuration for " + config.pole) | |
configMap.get(config.pole).foreach(item => println("Mapping over existing config to unsubscribe")) | |
configMap + (config.pole -> config) | |
} | |
.subscribe(configurations) | |
poleSubject.onNext("L01") | |
poleSubject.onNext("R02") | |
poleSubject.onNext("L99") | |
sealed trait Pole | |
case object LeftPole extends Pole | |
case object RightPole extends Pole | |
case class Config(pole: Pole, data: String) | |
} | |
/** | |
* Output: | |
* Configurations: Map() | |
* Receiving configuration for LeftPole | |
* Configurations: Map(LeftPole -> Config(LeftPole,Lefty! L01)) | |
* Receiving configuration for RightPole | |
* Configurations: Map(LeftPole -> Config(LeftPole,Lefty! L01), RightPole -> Config(RightPole,Poling to the right... R02)) | |
* Receiving configuration for LeftPole | |
* Mapping over existing config to unsubscribe | |
* Configurations: Map(LeftPole -> Config(LeftPole,Lefty! L99), RightPole -> Config(RightPole,Poling to the right... R02)) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment