Swift Combine: Essential Operator, Learn about `flatMap()`

Let’s go and look at something very important, one of the most important transformation operators, which is called flatMap.

What is flatMap?

The flatMap operator can be used to flatten the multiple upstream publishers into a single downstream publisher.

Example

import Combinestruct School {
let name: String
let numberOfStudents: CurrentValueSubject<Int, Never>

init(name: String, numberOfStudents: Int) {
self.name = name
self.numberOfStudents = CurrentValueSubject(numberOfStudents)
}
}let citySchool = School(name: "Fountain Head School", numberOfStudents: 100)let school = CurrentValueSubject<School, Never>(citySchool)school
.flatMap {
$0.numberOfStudents
}
.sink {
print($0)
}
citySchool.numberOfStudents.value += 1 // 101
school.value.numberOfStudents.value += 1 // 102

Go ahead and create a structure. It has two properties.

name with String Data Type,

numberOfStudents with CurrentValueSubject.

CurrentValueSubject is a kind of a publisher or subject which can be a publisher as well as a subscriber. It is going to be getting the Integer value. And it won’t fail. (<,Never>).

So, numberOfStudents is not an integer but a publisher which can publish a single value.

I also created school publisher with CurrentValueSubject and subscribe to school right away.

When numberOfStudents property changes, your school publisher are getting fired.

And when school publishes an event, school.flatMap().sink() is also getting fired.

So, flatMap() will take in the streams of data, which is coming from the internal publications events, and it will allow you to access those events.

That’s the whole use of that flatMap() operator.

Conclusion

  • When you use flatMap() operator, every data stream will send a notification of data changes.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
KD Knowledge Diet

Software Engineer, Mobile Developer living in Seoul. I hate people using difficult words. Why not using simple words? Keep It Simple Stupid!