Data Retrieving In Android Not Working Properly

  Kiến thức lập trình

I am working on a streak counter functionality, the streak counting logic is working fine, but the data for last lkogin date and last streak is not being fetched proplerly. What could be the possible reason for it?

The function for dat retrieval in viewModel is:

suspend fun streakDataHandler(givenType: String = "lastDate"): AppData? {
        val lastDateData: Flow<AppData?> = appDataRepository.getDataStream(givenType)
            .map { dataList ->
                dataList.firstOrNull()
            }
        val coroutineScope = CoroutineScope(Dispatchers.Main)
        var data: AppData? = null
        coroutineScope.launch {
            lastDateData.collect { appData ->
                if (appData != null) {
                    data = appData
                }
                else {
                    data = null
                }
            }
        }
        return data
    }

And the code to retrieve and use the data inside the composable file is:

val currentRetrievedDate: Date = Date()
    val currentDate: String = SimpleDateFormat("dd-MM-yyyy").format(currentRetrievedDate)

    var lastDateObject: AppData? = null
    LaunchedEffect(Unit) {
        lastDateObject = streakCounterViewModel.streakDataHandler()
    }
    var lastDate: String = "00-00-0000"
    if (lastDateObject != null) {
        lastDate = lastDateObject!!.content
    }

    var currentStreakObject: AppData? = null
    LaunchedEffect(Unit) {
        currentStreakObject = streakCounterViewModel.streakDataHandler("currentStreak")
    }
    var currentStreak: String = "0"

    if (currentStreakObject != null) {
        currentStreak = currentStreakObject!!.content
    }

Note: This composable file isn’t used for displaying the streak, it just calculates it (and updates it in the local database) and returns the value of steak to another composable which displays it.
There is on problem on streak calculation logic as I’ve tested it separately. The problem most probably only lies within data retrieval.

The full project is on github: https://github.com/tauqirnizami/HealthEase

LEAVE A COMMENT