Skip to content

Commit a21e940

Browse files
authored
Merge pull request eugenp#4988 from shreyasm/forked1
BAEL-1875 - Shreyas Mahajan - Adding unit tests for comparing flatmap and switchmap in RxJava
2 parents 3d3dfd7 + 36ec931 commit a21e940

1 file changed

Lines changed: 65 additions & 0 deletions

File tree

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
package com.baeldung.rxjava.operators;
2+
3+
import io.reactivex.Observable;
4+
import io.reactivex.schedulers.TestScheduler;
5+
import org.junit.Test;
6+
7+
import java.util.ArrayList;
8+
import java.util.Arrays;
9+
import java.util.List;
10+
import java.util.concurrent.TimeUnit;
11+
12+
import static org.hamcrest.CoreMatchers.hasItems;
13+
import static org.junit.Assert.assertEquals;
14+
import static org.junit.Assert.assertThat;
15+
16+
public class RxFlatmapAndSwitchmapUnitTest {
17+
@Test
18+
public void givenObservable_whenFlatmap_shouldAssertAllItemsReturned() {
19+
//given
20+
List<String> actualOutput = new ArrayList<>();
21+
final TestScheduler scheduler = new TestScheduler();
22+
final List<String> keywordToSearch = Arrays.asList("b", "bo", "boo", "book", "books");
23+
24+
//when
25+
Observable.fromIterable(keywordToSearch)
26+
.flatMap(s -> Observable
27+
.just(s + " FirstResult", s + " SecondResult")
28+
.delay(10, TimeUnit.SECONDS, scheduler))
29+
.toList()
30+
.doOnSuccess(s -> actualOutput.addAll(s))
31+
.subscribe();
32+
33+
scheduler.advanceTimeBy(1, TimeUnit.MINUTES);
34+
35+
//then
36+
assertThat(actualOutput, hasItems("b FirstResult", "b SecondResult",
37+
"boo FirstResult", "boo SecondResult",
38+
"bo FirstResult", "bo SecondResult",
39+
"book FirstResult", "book SecondResult",
40+
"books FirstResult", "books SecondResult"));
41+
}
42+
43+
@Test
44+
public void givenObservable_whenSwitchmap_shouldAssertLatestItemReturned() {
45+
//given
46+
List<String> actualOutput = new ArrayList<>();
47+
final TestScheduler scheduler = new TestScheduler();
48+
final List<String> keywordToSearch = Arrays.asList("b", "bo", "boo", "book", "books");
49+
50+
//when
51+
Observable.fromIterable(keywordToSearch)
52+
.switchMap(s -> Observable
53+
.just(s + " FirstResult", s + " SecondResult")
54+
.delay(10, TimeUnit.SECONDS, scheduler))
55+
.toList()
56+
.doOnSuccess(s -> actualOutput.addAll(s))
57+
.subscribe();
58+
59+
scheduler.advanceTimeBy(1, TimeUnit.MINUTES);
60+
61+
//then
62+
assertEquals(2, actualOutput.size());
63+
assertThat(actualOutput, hasItems("books FirstResult", "books SecondResult"));
64+
}
65+
}

0 commit comments

Comments
 (0)