Skip to content

Commit

Permalink
Create ViewModel for TasksList.
Browse files Browse the repository at this point in the history
  • Loading branch information
maisawr committed Feb 21, 2024
1 parent c9272ed commit b3f999b
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions app/src/main/java/com/example/pa/ui/todolist/TasksListViewModel.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.example.pa.ui.todolist

import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.asLiveData
import androidx.lifecycle.viewModelScope
import com.example.pa.data.DatabaseRepository
import com.example.pa.data.local.Tasks
import kotlinx.coroutines.launch

class TasksListViewModel(private val repository: DatabaseRepository): ViewModel() {
// Use LiveData to return the tasks
val allTasks: LiveData<List<Tasks>> = repository.allTasks.asLiveData()

fun insertTask(task: Tasks) = viewModelScope.launch {
repository.insert(task)
}
}

class TasksListViewModelFactory(private val repository: DatabaseRepository) :
ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(TasksListViewModel::class.java)) {
@Suppress("UNCHECKED_CAST")
return TasksListViewModel(repository) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}

0 comments on commit b3f999b

Please sign in to comment.