1+ package com.coolkie.noteultra.data
2+
3+ import android.content.Context
4+ import androidx.lifecycle.ViewModel
5+ import androidx.lifecycle.ViewModelProvider
6+ import androidx.lifecycle.viewModelScope
7+ import androidx.room.Dao
8+ import androidx.room.Database
9+ import androidx.room.Delete
10+ import androidx.room.Entity
11+ import androidx.room.Insert
12+ import androidx.room.PrimaryKey
13+ import androidx.room.Query
14+ import androidx.room.Room
15+ import androidx.room.RoomDatabase
16+ import kotlinx.coroutines.flow.Flow
17+ import kotlinx.coroutines.flow.SharingStarted
18+ import kotlinx.coroutines.flow.stateIn
19+ import kotlinx.coroutines.launch
20+
21+ @Entity(tableName = " notes" )
22+ data class Note (
23+ @PrimaryKey(autoGenerate = true ) val id : Int = 0 ,
24+ val title : String ,
25+ val content : String ,
26+ val date : Long
27+ )
28+
29+ @Dao
30+ interface NotesDao {
31+ @Insert
32+ suspend fun insert (note : Note )
33+
34+ @Delete
35+ suspend fun delete (note : Note )
36+
37+ @Query(" SELECT * FROM notes ORDER BY date DESC" )
38+ fun getAllNotes (): Flow <List <Note >>
39+ }
40+
41+ @Database(entities = [Note ::class ], version = 1 )
42+ abstract class NotesDatabase : RoomDatabase () {
43+ abstract fun noteDao (): NotesDao
44+
45+ companion object {
46+ @Volatile
47+ private var INSTANCE : NotesDatabase ? = null
48+
49+ fun getDatabase (context : Context ): NotesDatabase {
50+ return INSTANCE ? : synchronized(this ) {
51+ val instance = Room .databaseBuilder(
52+ context.applicationContext,
53+ NotesDatabase ::class .java,
54+ " notes_database"
55+ ).build()
56+
57+ INSTANCE = instance
58+ instance
59+ }
60+ }
61+ }
62+ }
63+
64+ class NoteViewModel (private val database : NotesDatabase ) : ViewModel() {
65+ val noteList = database.noteDao().getAllNotes()
66+ .stateIn(viewModelScope, SharingStarted .WhileSubscribed (5000 ), emptyList())
67+
68+ fun addNote (title : String , content : String , date : Long ) {
69+ val note = Note (title = title, content = content, date = date)
70+ viewModelScope.launch {
71+ database.noteDao().insert(note)
72+ }
73+ }
74+
75+ fun deleteNote (note : Note ) {
76+ viewModelScope.launch {
77+ database.noteDao().delete(note)
78+ }
79+ }
80+ }
81+
82+ class NoteViewModelFactory (private val database : NotesDatabase ) : ViewModelProvider.Factory {
83+ @Suppress(" UNCHECKED_CAST" )
84+ override fun <T : ViewModel > create (modelClass : Class <T >): T {
85+ if (modelClass.isAssignableFrom(NoteViewModel ::class .java)) {
86+ return NoteViewModel (database) as T
87+ }
88+ throw IllegalArgumentException (" Unknown ViewModel class" )
89+ }
90+ }
0 commit comments