Newer
Older
DevRealm / app / src / main / java / jackall / devrealm / viewmodel / MainViewModel.kt
MatsumotoKeiju on 8 Nov 2017 1 KB [add] Update adapter when db changes
package jackall.devrealm.viewmodel

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<ItemViewModel>()
        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() {
        override fun <T : ViewModel?> create(modelClass: Class<T>): T {
            return MainViewModel() as T
        }
    }
}