How do I build a flow from Room database but also processing the values prior?

I’m very new to Android Development.

I have a Room database of results:

@Entity(tableName = "results")
data class Result(
    @PrimaryKey(autoGenerate = true)
    val id: Int = 0,
    val result : Float,
    val date : String
)

@Database(
    entities = [Result::class],
    version = 1,
    exportSchema = false
)
abstract class ResultDatabase : RoomDatabase() {
    abstract fun resultDao() : ResultDao

    companion object {
        @Volatile
        private var Instance : ResultDatabase? = null

        fun getDatabase(context : Context) : ResultDatabase {
            return Instance ?: synchronized(this) {
                Room.databaseBuilder(context, ResultDatabase::class.java, "result_database")
                    .fallbackToDestructiveMigration()
                    .build()
                    .also { Instance = it }
            }
        }
    }
}

With a DAO

@Dao
interface ResultDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(result : Result)

    @Update
    suspend fun update(result : Result)

    @Delete
    suspend fun delete(result : Result)

    @Query("SELECT * FROM results WHERE id = :id")
    fun getResult(id : Int) : Flow<Result>

    @Query("SELECT * FROM results ORDER BY date ASC")
    fun getAllResults() : Flow<List<Result>>
}

and a Repository

class ResultRepository(private val resultDao : ResultDao) {

    fun getAllResults(): Flow<List<Result>> = resultDao.getAllResults()

    suspend fun getResultsSmoothed(numSteps : Int) : List<Result> {

        var allResults : List<Result> = listOf()
        getAllResults().collect { result -> allResults = allResults + result }

        val minDate = LocalDateTime.parse(allResults.first().date)
        val maxDate = LocalDateTime.parse(allResults.last().date)

        val period = Duration.between(minDate, maxDate)

        var step = period.seconds / numSteps

        var hundredResults = listOf<Result>()

        var nextDate = minDate

        for (i in 0..numSteps) {

            val resultPrior = allResults.fold(allResults.first()) { acc: Result, r ->
                val rd = LocalDateTime.parse(r.date)
                if (rd <= nextDate && (rd > LocalDateTime.parse(acc.date))) r
                else acc
            }

            val resultAfter = allResults.fold(allResults.last()) { acc: Result, r ->
                val rd = LocalDateTime.parse(r.date)
                if (rd > nextDate && (rd <= LocalDateTime.parse(acc.date))) r
                else acc
            }

            if (resultAfter == resultPrior) {
                val newResult = Result(date = nextDate.toString(), result = resultPrior.result)
                hundredResults = hundredResults + newResult
            } else {

                val resultPriorDate = LocalDateTime.parse(resultPrior.date)
                val resultAfterDate = LocalDateTime.parse(resultAfter.date)
                val periodBetween = Duration.between(resultPriorDate, resultAfterDate)

                val periodOver = Duration.between(resultPriorDate, nextDate)

                val percentageOver =
                    periodOver.seconds.toDouble() / periodBetween.seconds.toDouble();

                val resultDifference = resultAfter.result - resultPrior.result;
                val increaseToPriorAmount = resultDifference.toDouble() * percentageOver;

                val stepResult = resultPrior.result + increaseToPriorAmount;

                val newResult = Result(date = nextDate.toString(), result = stepResult.toFloat())
                hundredResults = hundredResults + newResult
            }
            nextDate = nextDate.plusSeconds(step)
        }

        return hundredResults
    }

    suspend fun getResultLabels(numLabels : Int) : List<String> {

        var allResults : List<Result> = listOf()
        getAllResults().collect { result -> allResults = allResults + result }

        val minDate = LocalDateTime.parse(allResults.first().date)
        val maxDate = LocalDateTime.parse(allResults.last().date)

        val period = Duration.between(minDate, maxDate)

        val step = period.seconds / numLabels

        var dateLabels = listOf<String>()

        var nextDate = minDate

        for (i in 0..numLabels) {
            val formatter = DateTimeFormatter.ofPattern("d MMM yy")
            dateLabels = dateLabels + nextDate.format(formatter)
            nextDate = nextDate.plusSeconds(step)
        }

        return dateLabels
    }

    @Suppress("RedundantSuspendModifier")
    @WorkerThread
    suspend fun insertResult(result : Result) {
        resultDao.insert(result)
    }

    @Suppress("RedundantSuspendModifier")
    @WorkerThread
    suspend fun updateResult(result : Result) {
        resultDao.update(result)
    }

    @Suppress("RedundantSuspendModifier")
    @WorkerThread
    suspend fun deleteResult(result : Result) {
        resultDao.delete(result)
    }
}

The two functions getResultLabels and getResultsSmoothed are processing some values from the database and returning things. The reason I put this in here was to provide it to the view model because I’ve understood that I shouldn’t do this processing in my composables.

Then my ViewModel

class ResultViewModel(private val repository: ResultRepository) : ViewModel() {

    val allResults = repository.getAllResults()

    fun getSmoothedResults(num : Int) : Flow<List<Result>> {
        return flow {
            val results = repository.getResultsSmoothed(num)
            Log.d("ME vm", results.toString())
            emit(results)
        }
    }

    fun getResultLabels(num : Int) : Flow<List<String>> {
        return flow { emit(repository.getResultLabels(num)) }
    }

    fun update(result : Result) = viewModelScope.launch {
        repository.updateResult(result)
    }

    fun delete(result : Result) = viewModelScope.launch {
        repository.deleteResult(result)
    }

    fun insert(result : Result) = viewModelScope.launch {
        repository.insertResult(result)
    }
}

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

What I’m trying to do is put these Lists into Flows so that the composables that use them will automatically update.

For example:

@Composable
fun Metrics(resultViewModel: ResultViewModel,
            resultList : List<Result>?) {

    if(resultList.isNullOrEmpty())
        return

    var dateLabels = resultViewModel.getResultLabels(5).collectAsState(initial = listOf())

    var hundredResults = resultViewModel.getSmoothedResults(100).collectAsState(
        initial = listOf()
    )

    Log.d("memememe", hundredResults.value.toString())

    Column()
    {
        LineChart(
            modifier = Modifier
                .fillMaxWidth()
                .height(300.dp)
                .padding(top = 12.dp, end = 12.dp),
            linesChartData = listOf(LineChartData(
                lineDrawer = SolidLineDrawer(color = MaterialTheme.colorScheme.onBackground),
                points = hundredResults.value.map {
                    LineChartData.Point(it.result, it.id.toString())
                })),
            animation = simpleChartAnimation(),
            pointDrawer = com.github.tehras.charts.line.renderer.point.NoPointDrawer,
            labels = dateLabels.value,
            xAxisDrawer = SimpleXAxisDrawer(
                axisLineThickness = 1.dp,
                axisLineColor = MaterialTheme.colorScheme.onBackground,
                labelTextColor = MaterialTheme.colorScheme.onBackground
            ),
            yAxisDrawer = SimpleYAxisDrawer(
                axisLineThickness = 1.dp,
                axisLineColor = MaterialTheme.colorScheme.onBackground,
                labelTextColor = MaterialTheme.colorScheme.onBackground
            )
        )
        DataTable(
            modifier = Modifier.fillMaxWidth(),
            columns = listOf(
                DataColumn(
                    width = TableColumnWidth.Fixed(60.dp)
                ) {
                    Text("")
                },
                DataColumn {
                    Text("Date")
                },
                DataColumn {
                    Text("Result")
                }
            )
        ) {
            resultList.forEach { r ->
                row {
                    cell {
                        IconButton(onClick = { resultViewModel.delete(r) }) {
                            Icon(Icons.TwoTone.Delete, "Delete result")
                        }
                    }
                    cell {
                        Text(
                            text = LocalDateTime.parse(r.date)
                                .format(DateTimeFormatter.ofPattern("dd MMM yyyy"))
                        )
                    }
                    cell {
                        Text("${r.result}")
                    }
                }
            }
        }
    }
}

However, my log call has an empty list. I may be approaching this problem completely wrong, but I’m unsure. I’m a little confused about the use of coroutines and state, and how these interact.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật