I'm attempting to write a custom delegate which would clean up the syntax for databinding in a Kotlin class. It would eliminate the need to define a custom getter and setter for every property I might want to observe.
The standard implementation in Kotlin appears to be as follows:
class Foo : BaseObservable() {
var bar: String
#Bindable get() = bar
set(value) {
bar = value
notifyPropertyChanged(BR.bar)
}
}
Clearly, with a lot of properties this class can become pretty verbose. What I would like instead is to abstract that away into a delegate like so:
class BaseObservableDelegate(val id: Int, private val observable: BaseObservable) {
#Bindable
operator fun getValue(thisRef: Any, property: KProperty<*>): Any {
return thisRef
}
operator fun setValue(thisRef: Any, property: KProperty<*>, value: Any) {
observable.notifyPropertyChanged(id)
}
}
Then, the class which extends BaseObservable could go back to having one-line variable declarations:
class Foo : BaseObservable() {
var bar by BaseObservableDelegate(BR.bar, this)
}
The problem is that without the #Bindable annotation in the Foo class, no propertyId is generated in BR for bar. I'm unaware of any other annotation or method for generating that property id.
Any guidance would be appreciated.
You can annotate the default getter or setter without providing a body.
var bar: String by Delegates.observable("") { prop, old, new ->
notifyPropertyChanged(BR.bar)
}
#Bindable get
There is a shortcut annotation use-site target which does the same thing.
#get:Bindable var bar: String by Delegates.observable("") { prop, old, new ->
notifyPropertyChanged(BR.bar)
}
Additionaly to the accepted answer - sometimes you need variables passed in constructor. It is easy to do too.
class Foo(_bar: String) : BaseObservable() {
#get:Bindable var bar by Delegates.observable(_bar) { _, _, _ ->
notifyPropertyChanged(BR.bar)
}
}
Sometimes we have to save object using parcel, I had some problems using delegete, so code looks like this:
#Parcelize
class Foo(private var _bar: String) : BaseObservable(), Parcelable {
#IgnoredOnParcel
#get:Bindable var bar
get() = _bar
set(value) {
_bar = value
notifyPropertyChanged(BR.bar)
}
}
I considered using the androidx.databinding.ObservableField wrapper for my fields. However, it was quite annoying having to read the values as field.get() and write them field.set(value) from the Kotlin code. Also, this approach does require special converters for serialization if you are using it with Retrofit or Room Database.
Finally, I came up with the below approach which allows me to define the variable in a single line as oppose to the accepted answer and keep the field to their default type without any wrapper. Thanks to the Kotlins property delegation. Now, I don't have to write converters for the serialization and have all the benefit from databinding.
class ObservableField<T : BaseObservable, V>(initialValue: V, private val fieldId: Int = -1) : ReadWriteProperty<T, V> {
private var value: V = initialValue
override fun getValue(thisRef: T, property: KProperty<*>): V {
return value
}
override fun setValue(thisRef: T, property: KProperty<*>, value: V) {
this.value = value
if (fieldId == -1) {
thisRef.notifyChange()
} else {
thisRef.notifyPropertyChanged(fieldId)
}
}
}
class Credential: BaseObservable() {
var username: String by ObservableField("")
#get:Bindable var password: String by ObservableField("", BR.password)
}
Related
Whenever I am trying to delegate my viewmodel using the delegated property in my Fragments
val viewModel:NewsViewModel by activityViewModels<> { }
This is the error I would receive.
Property delegate must have a 'getValue(BreakingNews, KProperty*>)' method. None of the following functions are suitable.
Lazy<NewsViewModel>.getValue(Any?, KProperty<*>)
where T = NewsViewModel for inline operator fun <T> Lazy<T>.getValue(thisRef: Any?, property:
KProperty<*>): T defined in kotlin
However, instantiating the viewmodel instance in the MainActivity this way, seems fine
val viewmodelFactory = ViewModelProviderFactory(dataRepo)
viewModel = ViewModelProvider(this,viewmodelFactory).get(NewsViewModel::class.java)
I assumed at first it may be due to the viewmodelFactory which is as follows.
class ViewModelProviderFactory(val Repo:NewsRepository): ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>,extras: CreationExtras): T {
return NewsViewModel(Repo) as T
}
}
The code below are the properties in my ViewModel, This is odd as I have cross-referred from multiple sources including the official `docs.
var breakingNews: MutableLiveData<Resource<ArticleList>> = MutableLiveData()
var breakingNewsPage = 1
var breakingNewsResponse: ArticleList? = null
var searchNews: MutableLiveData<Resource<ArticleList>> = MutableLiveData()
var searchNewsPage = 1
var searchNewsResponse: ArticleList? = null
var savedNumerics = 0
var _status = MutableLiveData<String>()
....
}
Usually, you want just val viewModel:NewsViewModel by activityViewModels().
In your case, with val viewModel:NewsViewModel by activityViewModels<> { }, you skipped two things.
First, you are attempting to provide a value for the extrasProducer parameter to the activityViewModels() function. However, that lambda expression needs to evaluate to a CreationExtras object, and yours evaluates to Unit.
Second, you failed to provide a type. AFAIK, <> is not going to be valid syntax here. Either leave the <> off (and the compiler should infer the type from the property type) or fully qualify it as <NewsViewModel>. I think this is the cause of your specific syntax error, but even if you fix this, you should then run into a problem with your empty lambda expression.
I understand there are two ways for lazy initialization in kotlin. first by lateinit which is dynamic but it is only for var. second, by lazy delegate which is for val but it is static, which means it can't be initialized at runtime.
I was wondering is there a way to have lazy dynamic initialization for immutable properties(val)????
property delegation also works like lazy and even if we define a custom delegate, its always static initialization. (to my knowledge)
is there a workaround for this? could it be implemented somehow?
so what I wish for, is something like lateinit val, shown in below code:
class MyClass: SomeCallback {
private lateinit val myData: String
override fun onStatusChanged(status: Status, data: String) {
if(status == Status.DataConfirmed ) {
myData = data
}
}
}
The best I can come up with is a read-write property delegate that throws if you access it before setting it, or if you set it multiple times. Kotlin doesn't let you lateinit a val. This is likely because it would be nonsensical to call a setter for a property that doesn't have one. I doubt they want to introduce the can of worms it would be to directly set the value of a backing field from anywhere besides the initializer, because it would be ambiguous.
A delegate like this should be adequate. If it's not adequate to help you immediately fix the bug of calling the setter multiple times, I would say that's a code smell that the class is too complicated and needs to be broken up into smaller units.
class Once<T>: ReadWriteProperty<Any, T> {
private object UNINITIALIZED
private var _value: Any? = UNINITIALIZED
override fun getValue(thisRef: Any, property: KProperty<*>): T {
if (_value !== UNINITIALIZED) {
#Suppress("UNCHECKED_CAST")
return _value as T
}
throw UninitializedPropertyAccessException("Property [$property] was accessed before it was initialized.")
}
override fun setValue(thisRef: Any, property: KProperty<*>, value: T) {
if (_value === UNINITIALIZED) {
_value = value
} else {
error("Cannot set property [$property] more than once.")
}
}
}
Is there a way to add multiple type parameters for generic functions?
I have two data classes who have some fields the same, and I want to compare them with only one function. Something like this:
data class ClassA{
val field: String?
...
}
data class ClassB{
val field: String?
...
}
And generic function should be something like:
private fun <T> mapSomething(model: T): String
where T : ClassA,
T: ClassB {
// do something with model.field and return String
}
But I get
Only one of the upper bounds can be a class
Is there a way to have two classes as upper bounds?
The problem is that multiple type bounds (which use exactly this syntax) are connected by "and", not "or". So T would need to be a subtype of both ClassA and ClassB, which is of course impossible. And currently there's no way to do "or". In future Kotlin might get union types, which would let you write T : ClassA | ClassB, but I wouldn't expect
val x: ClassA | ClassB = ...
x.field
to work even then, instead you will probably have to
val x: ClassA | ClassB = ...
when(x) {
is ClassA -> // use ClassA.field
is ClassB -> // use ClassB.field
}
But if you own ClassA and ClassB, you can just add an interface:
interface HasField {
val field: String?
}
data class ClassA : HasField {
override val field: String?
...
}
data class ClassB : HasField {
override val field: String?
...
}
Or alternatively:
private fun <T> mapSomething(model: T, getField: (T) -> String?): String {
...
}
and pass ClassA::field or ClassB::field respectively.
What is the most convenient way to use SLF4J or other logging approaches with kotlin?
Usually the developer is busy with boilerplate code like
private val logger: Logger = LoggerFactory.getLogger(this::class.java)
in each and every class to get a proper logger?
What are the most convenient ways to unify/simplify this with Kotlin?
You can define an extension property on every type:
val <T : Any> T.logger: Logger
get() = LoggerFactory.getLogger(this::class.java)
use it as follows:
class X {
init {
logger.debug("init")
}
}
Here's a simple example which returns a lazily-initialized logger from a bound callable reference or a standard property. I prefer calling from a callable reference because the :: denotes reflection (related to logging).
The class which provides the Lazy<Logger>:
class LoggingProvider<T : Any>(val clazz: KClass<T>) {
operator fun provideDelegate(inst: Any?, property: KProperty<*>) =
lazy { LoggerFactory.getLogger(clazz.java) }
}
Inline functions to call them:
inline fun <reified T : Any> KCallable<T>.logger() =
LoggingProvider(T::class)
inline fun <reified T : Any> T.logger() =
LoggingProvider(T::class)
Here's an example of using them. The require assertion in the initializer shows that the loggers share a reference:
class Foo {
val self: Foo = this
val logger by this.logger()
val callableLogger by this::self.logger()
init {
require(logger === callableLogger)
}
}
I define this function in my projects to make defining a logger easier for me. It takes advantage of Kotlin's reified types.
// Defined in Utilities.kt
inline fun <reified T:Any> logFor() =
LoggerFactory.getLogger(T::class.java)
Usage:
class MyClass {
private val log = logFor<MyClass>()
...
}
Or if you are creating a lot of them:
class MyClass {
companion object {
private val log = logFor<MyClass>()
}
...
}
if you don't like the boilerplate, you can always wrap the log.info with your own logger helper:
mylog.info(this, "data that needs to be logged")
Then in the background, have some sort of hashmap that keeps track of classes of the this param that can instantiate a logger for that class.
Other options might be using AspectJ Weaving to weave a logger into each class, but this is overkill in my opinion.
I have defined a utility method for this
fun getLogger(cl: KClass<*>): Logger {
return LoggerFactory.getLogger(cl.java)!!
}
and now in each class I can use the logger like this
companion object {
private val logger = getLogger(MyClass::class)
}
Lets say I have a Kotlin class similar to this:
class MyKotlinExample {
val mMyString = MutableLiveData<String>()
}
MutableLiveData extends LiveData however I don't want to expose MutableLiveData to other classes. They should only see/access LiveData<String> as my special String
Is it possible, and/or good/advised etc?
You can use a backing property:
class MyKotlinExample {
private val _myString = MutableLiveData<String>()
val myString: LiveData<String>
get() = _myString
}
You can also provide an interface to your clients, which provides only LiveData<String>. Given the following classes:
interface LiveData<T> {
val value: T
}
data class MutableLiveData<T>(override var value: T) : LiveData<T>
Create the following interface/implementation:
interface MyExampleInterface {
val myString: LiveData<String>
}
class MyExampleClass : MyExampleInterface {
override val myString: MutableLiveData<String> = MutableLiveData("")
}
Internally, you can access myString as MutableLiveData, and you can pass the instance of MyExampleClass as MyExampleInterface so they can only access myString as LiveData<String>.
You should use a getter which does the cast for you:
class MyKotlinExample {
private val mMyString = MutableLiveData<String>()
fun getNonMutableLiveData(): LiveData<String> = mMyString
}
I would make the field private and expose the value like so:
class MyKotlinExample {
private val mMyString = MutableLiveData<String>()
fun getMyString(): String = mMyString.getValue()
}
Kotlin creators heard our voice and provided a simple way of doing this on Kotlin 1.7 :
private val item = MutableLiveData<Item>()
public get(): LiveData<Item>
or just:
val item = MutableLiveData <Item>()
get(): LiveData <Item>
Note: It is currently subject to opt-in and have limited support, so we will have to wait for a bit longer for stable release.
This is quite simple - you set the type of the property to LiveData<String>, but initialize it with the instance of MutableLiveData<String>:
class MyKotlinExample {
val mMyString: LiveData<String> = MutableLiveData<String>()
}