w3resource

Kotlin observable pattern: Implementing subscription events


Write a Kotlin object-oriented program that creates an interface Observable with methods subscribe and unsubscribe. Implement it in a class Publisher to allow objects to subscribe and unsubscribe from events.


Pre-Knowledge (Before You Start!)

Before attempting this exercise, you should be familiar with the following concepts:

  • Interfaces in Kotlin: Understanding how to define and implement interfaces with abstract methods.
  • Observer Pattern: The Observer Pattern is a design pattern where one object (the publisher) notifies other objects (observers) about changes.
  • Mutable List: Using a mutable list to store and manage a collection of observers in the Publisher class.
  • Methods: Implementing methods for subscribing and unsubscribing observers, as well as publishing events to observers.
  • Update Method: How an observer reacts to changes by implementing the update method.

Hints (Try Before Looking at the Solution!)

Try to solve the problem using these hints:

  • Hint 1: Define an interface Observable with methods subscribe and unsubscribe.
  • Hint 2: Create an Observer interface with an update method that the subscribing classes will implement.
  • Hint 3: Create a Publisher class that implements the Observable interface. Use a mutable list to store the observers.
  • Hint 4: Implement the subscribe and unsubscribe methods to add or remove observers from the list.
  • Hint 5: Define a method publishMessage in the Publisher class to send messages to all subscribed observers.
  • Hint 6: Create concrete observer classes like EmailNotification and SMSNotification that implement the Observer interface and provide custom logic in the update method.

Sample Solution:

Kotlin Code:

interface Observable {
    fun subscribe(observer: Observer)
    fun unsubscribe(observer: Observer)
}

interface Observer {
    fun update(message: String)
}

class Publisher : Observable {
    private val observers: MutableList<Observer> = mutableListOf()

    override fun subscribe(observer: Observer) {
        observers.add(observer)
        println("Observer ${observer.javaClass.simpleName} subscribed.")
    }

    override fun unsubscribe(observer: Observer) {
        observers.remove(observer)
        println("Observer ${observer.javaClass.simpleName} unsubscribed.")
    }

    fun publishMessage(message: String) {
        println("Publishing message: $message")
        observers.forEach { observer ->
            observer.update(message)
        }
    }
}

class EmailNotification : Observer {
    override fun update(message: String) {
        println("Email notification received: $message")
        // Logic to send an email notification
    }
}

class SMSNotification : Observer {
    override fun update(message: String) {
        println("SMS notification received: $message")
        // Logic to send an SMS notification
    }
}

fun main() {
    val publisher = Publisher()

    val emailNotification = EmailNotification()
    val smsNotification = SMSNotification()

    publisher.subscribe(emailNotification)
    publisher.subscribe(smsNotification)

    publisher.publishMessage("Hello, subscribers!")

    publisher.unsubscribe(emailNotification)

    publisher.publishMessage("Goodbye, subscribers!")
}

Sample Output:

Observer EmailNotification subscribed.
Observer SMSNotification subscribed.
Publishing message: Hello, subscribers!
Email notification received: Hello, subscribers!
SMS notification received: Hello, subscribers!
Observer EmailNotification unsubscribed.
Publishing message: Goodbye, subscribers!
SMS notification received: Goodbye, subscribers!

Explanation:

In the above exercise we have an Observable interface that defines the methods subscribe and unsubscribe. These methods allow objects to subscribe and unsubscribe from events.

The Observer interface defines the update method called when an event occurs.

Publisher Class: The Publisher class implements the Observable interface. It maintains a list of observers and provides subscribe and unsubscribe methods to manage them. The publishMessage method publishes a message to all subscribed observers. It calls the update method on each observer.

EmailNotification and SMSNotification classes: The EmailNotification and SMSNotification classes implement the Observer interface and define their own behavior in the update method.

In the "main()" function, we create an instance of the Publisher class. We also create instances of the EmailNotification and SMSNotification classes.

Subscribe: We then subscribe the emailNotification and smsNotification objects to the publisher by calling the subscribe method. After that, we publish a message using the publishMessage method of the publisher.

Unsubscribe: Next, we unsubscribe the emailNotification object from the publisher by calling the unsubscribe method. Finally, we publish another message using the publishMessage method.

Kotlin Editor:


Previous: Creating animal instances.
Next: Building hierarchical structures.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.