diff --git a/app/src/main/java/jackall/devrealm/viewmodel/MainViewModel.kt b/app/src/main/java/jackall/devrealm/viewmodel/MainViewModel.kt index 052c44c..a9e41b5 100644 --- a/app/src/main/java/jackall/devrealm/viewmodel/MainViewModel.kt +++ b/app/src/main/java/jackall/devrealm/viewmodel/MainViewModel.kt @@ -2,14 +2,55 @@ import android.arch.lifecycle.ViewModel import android.arch.lifecycle.ViewModelProvider +import android.databinding.BindingAdapter +import android.support.v7.widget.LinearLayoutManager +import android.support.v7.widget.RecyclerView +import jackall.devrealm.App +import jackall.devrealm.adapter.MainAdapter +import jackall.devrealm.db.PersonRealmHelper +import java.util.* /** * Created by matsumoto_k on 2017/11/08. */ class MainViewModel : LifecycleViewModel() { + var adapter: MainAdapter? = null + val personRealmHelper = PersonRealmHelper() + override fun onCreate() { super.onCreate() + val items = ArrayList() + 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) + } + } + } + adapter = MainAdapter(App.instance, items) + } + + override fun onDestroy() { + super.onDestroy() + personRealmHelper.close() + } + + object Adapter { + @JvmStatic + @BindingAdapter("android:setMainAdapter") + fun setMainAdapter(recyclerView: RecyclerView, adapter: MainAdapter?) { + if (adapter == null) + return + recyclerView.layoutManager = LinearLayoutManager(App.instance) + recyclerView.adapter = adapter + } } class Factory() : ViewModelProvider.NewInstanceFactory() {