i am having a template / generics question.
This is the code i have at the moment
data class RealmWatcher<T>(
val results: RealmResults<T>,
val handler: (RealmResults<T>) -> Unit)
And and using this in an Android fragment to listen to specific results and execute actions based on the changes. So lets take this as an example
private val realmListener = arrayOf(
RealmWatcher<Notification>(Realm.getDefaultInstance().where(Notification::class.java).equalTo("isNew", true).findAll(),
{ n: RealmResults<Notification> ->
// DO STUFF
})
I am doing this while start / stop of the fragment
override fun onResume() {
super.onResume()
// start listening and execute
realmListener.forEach { it.handler(it.results) }
realmListener.forEach { it.results.addChangeListener(it.handler) }
}
override fun onPause() {
// stop listening
realmListener.forEach { it.results.removeChangeListener(it.handler) }
super.onPause()
}
It works only when i am using one type (like Notification above). How should I define that if i want to use different types in the form of
private val realmListener = arrayOf(
RealmWatcher<Notification>(Realm.getDefaultInstance().where(Notification::class.java).equalTo("isNew", true).findAll(),
{ n: RealmResults<Notification> ->
// TODO STUFF
}),
RealmWatcher<Project>(Realm.getDefaultInstance().where(Project::class.java).equalTo("isOdd", true).findAll(),
{ n: RealmResults<Project> ->
// TODO STUFF
})
)
When mixing the types (Notification and Project) I will get a Type mismatch error.
And when defining the
private val realmListener:Array<RealmWatcher<out Any>>
I will also get Type mismatch errors
How can I define the Array to have several different RealmWatcher with different types T?
data class RealmWatcher<out T>Tis also used ininposition in the code. See my answer for a working solution that also encapsulates the logic better.