package com.xd.threadviewmodelkotlin

import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import kotlin.math.log

class MyViewModel : ViewModel() {
    private val items = arrayOf(
        "Chris Bailey-Kellogg",
        "Devin Balkcom", "Andrew Campbell", "Michael Casey",
        "Amit Chakrabarti", "Thomas H. Cormen ",
        "Robert L. (Scot) Drysdale, III", "Hany Farid", "Lisa Fleischer",
        "Gevorg Grigoryan", "Prasad Jayanti", "David Kotz", "Lorie Loeb",
        "Fabio Pellacini", "Daniel Rockmore", "Sean Smith",
        "Lorenzo Torresani", "Peter Winkler", "Emily Whiting", "Xia Zhou")

    var nameToShow = MutableLiveData<ArrayList<String>>()
    private val arrayList: ArrayList<String> = ArrayList()

    init {
//        nameToShow.value = arrayList
        val thread = Thread(){
            val handler = Handler(Looper.getMainLooper())
            for (item in items){
                val myRunnable = Runnable {
                    arrayList.add(item)
                    nameToShow.value = arrayList // note that value() needs to be called or the observer in the fragment won't be notified about the change. see https://stackoverflow.com/questions/47941537/notify-observer-when-item-is-added-to-list-of-livedata?rq=1
                } // code crashes if accessing nameToShow in a thread
                handler.post(myRunnable)
                Thread.sleep(1000)
            }
        }
        thread.start()
    }
}