Last active
February 13, 2018 11:23
-
-
Save umair13adil/447c9d470b59a0daf99161e91afa3d90 to your computer and use it in GitHub Desktop.
RxJava2 FlatMap,SwitchMap,ConcatMap TestCases in Kotlin
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
import io.reactivex.Observable | |
import io.reactivex.schedulers.TestScheduler | |
import org.junit.Test | |
import java.util.* | |
import java.util.concurrent.TimeUnit | |
class ExampleUnitTest { | |
@Test | |
@Throws(Exception::class) | |
fun flatMap() { | |
val scheduler = TestScheduler() | |
val delay = 100L | |
Observable.fromIterable(listOf("a", "b", "c", "d", "e", "f")) | |
.flatMap { | |
Observable.just(it + "x") | |
} | |
.delaySubscription(delay, TimeUnit.SECONDS, scheduler) | |
.filter { it.contains("c") } | |
.doOnNext() { | |
print("flatMap: ${it} \n") | |
} | |
.subscribe() | |
scheduler.advanceTimeBy(200, TimeUnit.SECONDS) | |
} | |
//Expected Result: cx | |
@Test | |
@Throws(Exception::class) | |
fun switchMap() { | |
val scheduler = TestScheduler() | |
Observable.fromIterable(listOf("a", "b", "c", "d", "e", "f")) | |
.switchMap({ s -> | |
val delay = Random().nextInt(10) | |
Observable.just<String>(s + "x") | |
.delay(delay.toLong(), TimeUnit.SECONDS, scheduler) | |
}) | |
.filter { it.contains("c") } | |
.doAfterNext { | |
print("switchMap: ${it}\n") | |
} | |
.subscribe() | |
scheduler.advanceTimeBy(1, TimeUnit.MINUTES) | |
} | |
//Expected Result: Empty | |
@Test | |
@Throws(Exception::class) | |
fun concatMap() { | |
val scheduler = TestScheduler() | |
Observable.fromIterable(listOf("a", "b", "c", "d", "e", "f")) | |
.concatMap({ s -> | |
val delay = Random().nextInt(10) | |
Observable.just<String>(s + "x") | |
.delay(delay.toLong(), TimeUnit.SECONDS, scheduler) | |
}) | |
.filter { it.contains("c") } | |
.doAfterNext { | |
print("concatMap: ${it}\n") | |
} | |
.subscribe() | |
scheduler.advanceTimeBy(1, TimeUnit.MINUTES) | |
} | |
//Expected Result: cx | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment