Here's a concise summary of the solution:
We define two entities, Parent and Child, with a foreign key relationship. The DAOs provide methods to interact with the database, and the ViewModel uses Flow to observe changes in the database. The ViewModel provides methods to initialize the list of children, add new children, add a list of children, and update children. All changes are saved in the Room database.
Entities
@Entity(tableName = "parents")
data class Parent(
@PrimaryKey val id: String,
val name: String
)
@Entity(
tableName = "children",
foreignKeys = [
ForeignKey(
entity = Parent::class,
parentColumns = ["id"],
childColumns = ["parentId"],
onDelete = ForeignKey.CASCADE
)
]
)
data class Child(
@PrimaryKey(autoGenerate = true) val id: Long = 0,
val name: String,
val parentId: String
)
DAOs
@Dao
interface ParentDao {
@Insert
suspend fun insert(parent: Parent)
@Query("SELECT * FROM parents WHERE id = :id")
suspend fun getParentById(id: String): Parent?
}
@Dao
interface ChildDao {
@Insert
suspend fun insert(child: Child)
@Insert
suspend fun insertAll(children: List<Child>)
@Update
suspend fun update(child: Child)
@Query("SELECT * FROM children WHERE parentId = :parentId")
fun getChildrenByParentId(parentId: String): Flow<List<Child>>
@Query("DELETE FROM children WHERE parentId = :parentId")
suspend fun deleteChildrenByParentId(parentId: String)
}
Database
@Database(entities = [Parent::class, Child::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun parentDao(): ParentDao
abstract fun childDao(): ChildDao
}
ViewModel
class MyViewModel(application: Application) : AndroidViewModel(application) {
private val db = Room.databaseBuilder(
application,
AppDatabase::class.java, "app-database"
).build()
private val childDao = db.childDao()
private val parentDao = db.parentDao()
private var currentParentId: String? = null
private val _children = MutableStateFlow<List<Child>>(emptyList())
val children: StateFlow<List<Child>> = _children
fun initializeChildren(parentId: String) {
currentParentId = parentId
viewModelScope.launch {
childDao.getChildrenByParentId(parentId).collect {
_children.value = it
}
}
}
fun addChild(child: Child) {
viewModelScope.launch {
childDao.insert(child)
}
}
fun addChildren(children: List<Child>) {
viewModelScope.launch {
childDao.insertAll(children)
}
}
fun updateChild(child: Child) {
viewModelScope.launch {
childDao.update(child)
}
}
override fun onCleared() {
super.onCleared()
db.close()
}
}
Usage Example
class MainActivity : AppCompatActivity() {
private lateinit var viewModel: MyViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewModel = ViewModelProvider(this).get(MyViewModel::class.java)
// Initialize with a parent ID
viewModel.initializeChildren("parent123")
// Observe changes in the children list
viewModel.children.onEach { children ->
// Update UI with the new list of children
}.launchIn(lifecycleScope)
// Add a new child
val newChild = Child(name = "Child 1", parentId = "parent123")
viewModel.addChild(newChild)
// Add a list of children
val childrenList = listOf(
Child(name = "Child 2", parentId = "parent123"),
Child(name = "Child 3", parentId = "parent123")
)
viewModel.addChildren(childrenList)
// Update a child
val updatedChild = Child(id = 1, name = "Updated Child", parentId = "parent123")
viewModel.updateChild(updatedChild)
}
}
This solution meets all the requirements: initializing the list with a foreign key, adding and updating elements, saving changes to the database, and using Flow to observe changes.