cloudroam
2025-02-25 0fce8fea0b83afb02b5d8780160787e87b8ceedb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.example.firstapp.ui.reminder
 
import androidx.lifecycle.*
import com.example.firstapp.database.entity.Reminder
import com.example.firstapp.database.repository.ReminderRepository
import kotlinx.coroutines.launch
 
class ReminderViewModel(private val repository: ReminderRepository) : ViewModel() {
 
    // 使用 Flow 获取所有提醒
    val allReminders: LiveData<List<Reminder>> = repository.allReminders.asLiveData()
 
    // 插入新提醒
    fun insertReminder(reminder: Reminder) = viewModelScope.launch {
        repository.insert(reminder)
    }
 
    // 删除提醒
    fun deleteReminder(reminder: Reminder) = viewModelScope.launch {
        repository.delete(reminder)
    }
}
 
// ViewModel Factory
class ReminderViewModelFactory(private val repository: ReminderRepository) : ViewModelProvider.Factory {
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(ReminderViewModel::class.java)) {
            @Suppress("UNCHECKED_CAST")
            return ReminderViewModel(repository) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }