https://kotlinlang.org logo
#codereview
Title
# codereview
t

tipsy

10/31/2019, 6:19 PM
i have a stupid problem. i need to detect changes to an object which i do not own. my code looks like this:
Copy code
private fun changeListener(obj: Any) {
    fun getObjectString(): String {
        val baos = ByteArrayOutputStream()
        ObjectOutputStream(baos).also { it.writeObject(obj) }.also { it.close() }
        return baos.toString()
    }

    var oldValue = getObjectString()
    Thread {
        while (true) {
            val newValue = getObjectString()
            if (oldValue != newValue) {
                println("Change detected")
                oldValue = newValue
            }
            Thread.sleep(250)
        }
    }.start()
}
f

furkan.akdemir

11/01/2019, 9:41 PM
@tipsy You can achieve it with
Delegates.observable()
Copy code
var name: String by Delegates.observable(_name) { _, oldName, newName ->
        println("Changed from $oldName to $newName")
        _name = newName
    }
t

tipsy

11/01/2019, 11:39 PM
thanks @furkan.akdemir - unfortunately it's a java object that already exists. somewhere in the codebase there is a
MyObject myObject = ...
i have access to
myObject
and want to know if it changes
d

Dominaezzz

11/02/2019, 2:24 PM
Not a solution but it's bothering me 😅.
ObjectOutputStream(baos).also { it.writeObject(obj) }.also { it.close() }
->
ObjectOutputStream(baos).use { it.writeObject(obj) }
.
👍 2
😅 1
3 Views