https://kotlinlang.org logo
p

Philipp Mayer

10/07/2020, 6:29 AM
What's a good use case for an observable delegate? I digged into it and I can't really find a good example where I would defintly choose this one over anything else. I'm a backend guy. A quick look at google suggests that it seems to be more of an android thing? I came up with the topic while preparing a little kotlin intro for our Java devs, and thought that I could also show the builtin delegates.
j

janvladimirmostert

10/07/2020, 7:56 AM
i used it in KotlinJS to create a change detection mechanism, although i created my own observable delegate since i needed a bit more than the standard Observable delegate so whenever i go blah = "new value", change detection triggers and it re-renders certain parts of a page. On the backend, mmm
something like this:
Copy code
var password: String? by Delegates.calculatable(
		onInput = { clearMessages() },
		getValue = { _password },
		setValue = { _password = it ?: "" },
		validate = {
			passwordError = null
			if (it.newValue?.isEmpty() == true) {
				valid = false
				passwordError = requiredFieldMessage
			}
			return@calculatable true
		},
		onChange = {
			changed(it.name)
		}
	)
i would say typical use-case is for the observer pattern, but then again, anything you can implement with the observer pattern, you can probably implement with regular code as well using the observer pattern probably just makes it more maintainable maybe a good use-case is websockets if you update a value in the backend, the observer trigers a push to the frontend syncing all relevant clients, all you have to do is make sure that your variable uses the delegate and the rest happens automagically
p

Philipp Mayer

10/07/2020, 11:26 AM
Yeah, websockets is a good example. I had a similar example: An mqtt client which fetches some sensor data and updates something when the value actually changed.
2 Views