diff --git a/app/src/main/java/jackall/devrealm/viewmodel/MainViewModel.kt b/app/src/main/java/jackall/devrealm/viewmodel/MainViewModel.kt index c0eef88..3f19c58 100644 --- a/app/src/main/java/jackall/devrealm/viewmodel/MainViewModel.kt +++ b/app/src/main/java/jackall/devrealm/viewmodel/MainViewModel.kt @@ -6,6 +6,8 @@ import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.View +import io.realm.OrderedRealmCollectionChangeListener +import io.realm.RealmResults import jackall.devrealm.App import jackall.devrealm.adapter.MainAdapter import jackall.devrealm.db.PersonRealmHelper @@ -19,22 +21,24 @@ var adapter: MainAdapter? = null val personRealmHelper = PersonRealmHelper() + lateinit var realmChangeListener: OrderedRealmCollectionChangeListener> override fun onCreate() { super.onCreate() val items = ArrayList() + realmChangeListener = OrderedRealmCollectionChangeListener { results, changeSet -> + changeSet.insertions.forEach { + adapter?.insert(ItemViewModel(results.get(it))) + } + changeSet.deletions.forEach { + adapter?.remove(it) + } + } personRealmHelper.findAll().apply { forEach { items.add(ItemViewModel(it)) } - addChangeListener { results, changeSet -> - changeSet.insertions.forEach { - adapter?.insert(ItemViewModel(results.get(it))) - } - changeSet.deletions.forEach { - adapter?.remove(it) - } - } + addChangeListener(realmChangeListener) } adapter = MainAdapter(App.instance, items) }