Scala Reactive Programming
上QQ阅读APP看书,第一时间看更新

FRP – the flatMap() function Marble diagram

We use the flatMap() function when we want to map a data stream of data stream elements into a plain data stream element.

For instance, List[List[Int]] to List[Int], as illustrated here:

scala> val numList = List(List(1,2,3),List(4,5),List(6)) 
numList: List[List[Int]] = List(List(1, 2, 3), List(4, 5), List(6)) 
 
scala> numList.map(x => x) 
res9: List[List[Int]] = List(List(1, 2, 3), List(4, 5), List(6)) 
 
scala> numList.flatMap(x => x) 
res10: List[Int] = List(1, 2, 3, 4, 5, 6) 

In this case, the map() function does not give us the expected results, so we only use flatMap(). We can represent this flatMap() function in a Marble diagram as follows: