Skip to content

Commit 03148a3

Browse files
committed
Add switchMap to RxScala
1 parent 2ba5fe8 commit 03148a3

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

language-adaptors/rxjava-scala/src/examples/scala/rx/lang/scala/examples/RxScalaDemo.scala

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1228,4 +1228,11 @@ class RxScalaDemo extends JUnitSuite {
12281228
}
12291229
o.subscribe(println(_))
12301230
}
1231+
1232+
@Test def switchMapExample() {
1233+
val o = Observable.interval(300 millis).take(5).switchMap[String] {
1234+
n => Observable.interval(50 millis).take(10).map(i => s"Seq ${n}: ${i}")
1235+
}
1236+
o.toBlocking.foreach(println)
1237+
}
12311238
}

language-adaptors/rxjava-scala/src/main/scala/rx/lang/scala/Observable.scala

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2237,6 +2237,23 @@ trait Observable[+T]
22372237
)
22382238
}
22392239

2240+
/**
2241+
* Returns a new Observable by applying a function that you supply to each item emitted by the source
2242+
* Observable that returns an Observable, and then emitting the items emitted by the most recently emitted
2243+
* of these Observables.
2244+
*
2245+
* <img width="640" height="350" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/switchMap.png">
2246+
*
2247+
* @param f a function that, when applied to an item emitted by the source Observable, returns an Observable
2248+
* @return an Observable that emits the items emitted by the Observable returned from applying a function to
2249+
* the most recently emitted item emitted by the source Observable
2250+
*/
2251+
def switchMap[R](f: T => Observable[R]): Observable[R] = {
2252+
toScalaObservable[R](asJavaObservable.switchMap[R](new Func1[T, rx.Observable[_ <: R]] {
2253+
def call(t: T): rx.Observable[_ <: R] = f(t).asJavaObservable
2254+
}))
2255+
}
2256+
22402257
/**
22412258
* Given an Observable that emits Observables, creates a single Observable that
22422259
* emits the items emitted by the most recently published of those Observables.

0 commit comments

Comments
 (0)