Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
RxJava2 FlatMap,SwitchMap,ConcatMap TestCases in Kotlin
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
You can’t perform that action at this time.