Merge pull request #9551 from MajewskiKrzysztof/KTLN-137

KTLN-137
This commit is contained in:
rpvilao 2020-06-28 20:10:26 +02:00 committed by GitHub
commit 33601cc191
6 changed files with 64 additions and 0 deletions

View File

@ -0,0 +1,18 @@
package com.baeldung.observer
import java.util.ArrayList
interface IObservable {
val observers: ArrayList<IObserver>
fun add(observer: IObserver) {
observers.add(observer)
}
fun remove(observer: IObserver) {
observers.remove(observer)
}
fun sendUpdateEvent() {
observers.forEach { it.update() }
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.observer
interface IObserver {
fun update()
}

View File

@ -0,0 +1,10 @@
package com.baeldung.observer.delegates
import kotlin.properties.Delegates
class BaeldungNewsletter {
val newestArticleObservers = mutableListOf<(String) -> Unit>()
var newestArticleUrl: String by Delegates.observable("") { _, _, newValue ->
newestArticleObservers.forEach { it(newValue) }
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.observer.delegates
fun main() {
val newsletter = BaeldungNewsletter()
newsletter.newestArticleObservers.add { newestArticleUrl ->
println("New Baeldung article: ${newestArticleUrl}")
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.observer.standard
import com.baeldung.observer.IObservable
import com.baeldung.observer.IObserver
import java.util.ArrayList
class BaeldungNewsletter : IObservable {
override val observers: ArrayList<IObserver> = ArrayList()
var newestArticleUrl = ""
set(value) {
field = value
sendUpdateEvent()
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.observer.standard
import com.baeldung.observer.IObserver
class BaeldungReader(private var newsletter: BaeldungNewsletter) : IObserver {
override fun update() {
println("New Baeldung article: ${newsletter.newestArticleUrl}")
}
}