Skip to content

Instantly share code, notes, and snippets.

@thomasweitzel
Created November 11, 2017 20:09
Show Gist options
  • Save thomasweitzel/b210c2dccbadb59d889bcea704a2b992 to your computer and use it in GitHub Desktop.
Save thomasweitzel/b210c2dccbadb59d889bcea704a2b992 to your computer and use it in GitHub Desktop.
Simple example of how to implement the Observable pattern in Kotlin with kotlin.properties.Delegates and Delegates.observable
import kotlin.properties.Delegates
interface Publisher {
fun onNews(news: String)
}
class RadioChannel : Publisher {
override fun onNews(news: String) = println("Heard on radio: $news")
}
class Newspaper : Publisher {
override fun onNews(news: String) = println("Read in newspaper: $news")
}
class NewsAgency {
private val listeners = mutableListOf<Publisher>()
var news: String by Delegates.observable(initialValue = "") { _, old, new ->
if (new != old) listeners.map { listener -> listener.onNews(new) }
}
fun subscribe(publisher: Publisher) = listeners.add(publisher)
fun unsubscribe(publisher: Publisher) = listeners.remove(publisher)
}
fun main(args: Array<String>) {
// Set up objects
val radioChannel = RadioChannel()
val newspaper = Newspaper()
val newsAgency = NewsAgency()
// Add listeners
newsAgency.subscribe(radioChannel)
newsAgency.subscribe(newspaper)
// Spread news, is redundant
newsAgency.news = "Celtics won!"
newsAgency.news = "Celtics won!"
newsAgency.news = "Celtics won!"
// Newspaper went out of business
newsAgency.unsubscribe(newspaper)
newsAgency.news = "Traffic jam on I93!"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment