I need to access the sum of all data and the last inserted data in real-time with SQL Delight, how to achieve real-time updated data without adding new table?
CREATE TABLE my_table(
id TEXT PRIMARY KEY NOT NULL,
name TEXT NOT NULL,
point REAL DEFAULT 0.0,
created_date TEXT NOT NULL
);
Get sum data:
getSum:
SELECT COALESCE(sum(point), 0) as total FROM my_table;
getLastData:
SELECT * FROM my_table ORDER BY created_date LIMIT 1;
Inside viewModel:
private val _lastInserted = MutableStateFlow<MyTable?>>(null)
val lastInserted: StateFlow<MyTable?> = _lastInserted.asStateFlow()
private val _sum = MutableStateFlow<GetSum?>>(null)
val sum: StateFlow<GetSum?> = _sum.asStateFlow()
fun getTotal(){
val result = repository.getSum()
viewModelScoped.launch{
result.collectLatest{ sum ->
_sum.value = sum
}
}
}
fun getLasData(){
val result = repository.getLastInserted()
viewModelScoped.launch{
result.collectLatest{ sum ->
_lastInserted.value = sum
}
}
}