package com.xd.listviewofprofscoroutinekotlin

import android.os.Handler
import android.os.Looper
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

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 var arrayList: ArrayList<String>

    init {
        arrayList = ArrayList()
        CoroutineScope(IO).launch{
            for(item in items){
                delay(1000)
                arrayList.add(item)
                updateProfListOnMainThread(arrayList)
            }
        }
    }

    private suspend fun updateProfListOnMainThread(arrayList: ArrayList<String>){
        withContext(Main){
            nameToShow.value = arrayList // note that value() needs to be called or the observer in the main activity 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 coroutine

}