The Observer pattern is a software design pattern uses to handle a one to many relationships between objects. In our example, we want a speaker to send a message to multiple audiences. For that, we need three classes as you guessed. We will be using Kotlin.
Speaker
The component responsible for creating or setting the message and notifying all the audiences. As you can see in the code below the Speaker has a message, a list of all the audiences subscribed to it and mechanisms to change the message and notify the audiences
class Speaker() {
private var message= Message("Hello")
private val audiences = ArrayList<Audience>()
fun setMessage(msg:String ) {
this.message.text = msg
notifyAudience()
}
fun addAudience(audience: Audience){
audiences.add(audience)
}
fun notifyAudience() {
for ( audience in audiences ) {
audience.update(message)
}
}
}
Message
The class representing the actual message to be sent.
class Message (public var text : String)
Audience
The audience waiting for the message and reacting or not to it. The Audience class has also a property message and function for updating it.
class Audience() {
private var message= Message("")
fun update(message: Message) {
this.message = message
print("Got a new message: ${message.text}\n")
}
}
Finally, the main function will look like this. We create a speaker then we add three audiences that will react to the message sent by the speaker. When a message is set One time the Many audiences subscribed to it react. Our program will output
Got a new message: Hello People!
Got a new message: Hello People!
Got a new message: Hello People!
Main function
fun main() {
// we create a speaker
val speaker = Speaker()
// we add three audiences to the speaker
speaker.addAudience(audience = Audience())
speaker.addAudience(audience = Audience())
speaker.addAudience(audience = Audience())
// set the message
speaker.setMessage("Hello People!")
}
How does this translate to RxJava?
Classes and interfaces are more complexes in Reactive programming but they use the same pattern for achieving the communication between objects.
- The Speaker is the *Observable
- The Audience is the Observer
- The Message is the Subject or Object emitted