Newer
Older
DevRealm / app / src / main / java / jackall / devrealm / viewmodel / MainViewModel.kt
MatsumotoKeiju on 8 Nov 2017 2 KB [add] Insert button, Remove Button
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 android.view.View
import jackall.devrealm.App
import jackall.devrealm.adapter.MainAdapter
import jackall.devrealm.db.PersonRealmHelper
import jackall.devrealm.vo.Person
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)
    }

    fun onClickAdd(view: View) {
        personRealmHelper.insert(
                Person(
                        age = Random().nextInt(100),
                        firstName = "firstName(${Random().nextInt(100)})",
                        lastName = "lastname(${Random().nextInt(100)})"
                )
        )
    }

    fun onClickRemove(view: View) {
        personRealmHelper.findLast().let { person ->
            if (person != null)
                personRealmHelper.delete(person)
        }
    }

    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
        }
    }
}