Leem
Leem

Reputation: 18308

Use my timer to get data in ViewModel (in kotlin)

I have a Foo class, which wraps a CountDownTimer:

class Foo() {
    private val timer = object: CountDownTimer(2000, 1000) {
        override fun onTick(millisUntilFinished: Long) {
            // How MyViewModel could utilize this callback to get students in MyViewModel?
        }

        override fun onFinish() {
        }
    }

    fun start() {
        myTimer.start()
    }
} 

In my ViewModel:

class MyViewModel constructor(repo: MyRepo): ViewModel() {
    fun getStudents(): LiveData<List<Student>> {
         // How to introduce my Foo class here to get student list every 2 seconds
         val studentList = liveData(Dispatchers.IO) {
             val studentList = repo.getStudents()
             emit(studentList)
         }
         return studentList
    }
}

I want to refactor MyViewModel code to get students every 2 seconds by using Foo class, but I am not sure how to do that. Could someone please guide me?

Upvotes: 2

Views: 5366

Answers (1)

Liem Vo
Liem Vo

Reputation: 5329

Here is an example

class Foo(private val viewModel: MyViewModel) {
    private val timer = object: CountDownTimer(2000, 1000) {
        override fun onTick(millisUntilFinished: Long) {
            viewModel.loadStudents()
        }

        override fun onFinish() {
        }
    }

    fun start() {
        timer.start()
    }
}

The Foo class holds an instance of ViewModel and can invoke the method loadStudents that will get the data from your repository

Here is the update of the ViewModel

class MyViewModel constructor(val repo: MyRepo): ViewModel() {

    private val _students = MutableLiveData<List<Student>>()
    val students: LiveData<List<Student>> // from your view (fragment or activity) observe this livedata
        get() = _students
    val foo = Foo(this)
    init {
        loadStudents()
    }

    fun loadStudents() {
        viewModelScope.launch(Dispatchers.IO){
            _students.postValue(repo.getStudents())
            foo.start()
        }
    }
}

The result responses from your repo.getStudents will be posted in the liveData that can be observed on your view.

Upvotes: 1

Related Questions