Home > Enterprise >  How to wait till observe returns results in android kotlin?
How to wait till observe returns results in android kotlin?

Time:03-18

i have this function in which it calls for an observe to check if there are data in table and if so returns them. Depending on the result i take the latest value and execute functions down the line.

Code Snippet

runBlocking {
            val job = lifecycleScope.launch {
            withContext(Dispatchers.Main) {
//1. first i need to wait here till observe returns results
            viewModel.getAllRatings(context).observe(viewLifecycleOwner) { items ->
                if (items.isNotEmpty()) {
                    rateVal = items[0].rateValue!!
                }
            }
        }
        }

            job.join()
//2. then only after first step done i need this to execute. 
        if (rateVal > 0) {
            ratingBar!!.rating = rateVal.toFloat()
        }
        }

getAllRatings()

fun getAllRatings(context: Context): LiveData<List<Rating>> {
        val dpDatabase = DPDatabase.getDPDatabase(context = context.applicationContext)
        feedbackSelectionRepository = FeedbackSelectionRepository(
            dpDatabase
        )
        allRating = feedbackSelectionRepository.allRatings
        return allRating
    }

In the current code however. the second function (2.) gets executed even before first part (1.) gets some results.

in debugger the flow goes as it comes to 1. then without waiting goes to 2. and then some results comes from 1.

I just need to await for results from observe. How can i do this? please help me with this

CodePudding user response:

Put the code for 2 inside the stuff you're doing in the observe callback. Then it will happen after the observe.

  • Related