1

That is what i'm trying to do; first showing items with loading progress in my ui, when is the api request returned as success then i'm manipulating my list for pass to recyclerview adapter.

So i need call repeatedly updateAndSetAdapterList function in coroutines.

Here is my code that calling same function in Fragment;

        lifecycleScope.launch(Dispatchers.IO) {
            // Videos
            viewModel.dashboardVideosFlow.collectLatest { flow ->
                when (flow) {
                    ...
                    is VideosFlow.DataReceived -> {
                        val row = SectionVideosBodyData(flow.videos)
                        updateAndSetAdapterList(1, row) <----
                    }
                }
            }
        }
    
        lifecycleScope.launch(Dispatchers.IO) {
            // Questions
            viewModel.dashboardQuestionsFlow.collectLatest { flow ->
                when (flow) {
                    ....
                    is QuestionsFlow.DataReceived -> {
                        val row = SectionQuestionsBodyData(flow.questions)
                        updateAndSetAdapterList(3, row) <----
                    }
                }
            }
        }

And this is the function that does something first on background thread after on main thread;

private suspend fun updateAndSetAdapterList(indexAt: Int? = null, row: BaseAdapterData? = null) {
    
    lifecycleScope.launch(Dispatchers.IO) {
            val newRows = mutableListOf<BaseAdapterData>()
            newRows.addAll(rows)
    
            if (indexAt != null && row != null) {
                newRows.removeAt(indexAt)
                newRows.add(indexAt, row)
            }
    
            withContext(Dispatchers.Main) {
                dashboardAdapter.submitList(newRows)
            }
    
            rows = newRows
        }
    }

I want to use synchronous api call functions but i want to use the ui update function as asynchronous that called from these synchronous functions.

  • 1
    What is missing or not working properly in your current implementation? Why do you need this `jobUpdateList`, `launch()` and `join()`? Seems unnecessary and I think you can remove them. One problem I see is that you mutate `rows` concurrently. To fix this problem, put whole your `updateAndSetAdapterList()` code into `Dispatchers.Main` (or better, use a mutex). – broot Jan 09 '23 at 23:18
  • @broot I'm sorry for that, i forgot the removing some lines that i tried before :) – murat_yuksektepe Jan 10 '23 at 07:26
  • I am not sure about what you are trying to achieve. What is the current problem? What is expected behavior and what is actual behavior? – Steyrix Jan 10 '23 at 09:35
  • https://stackoverflow.com/questions/75096507/run-sequential-jobs-functions-in-kotlin-coroutines-with-livedata here is a detailed version @Steyrix – murat_yuksektepe Jan 13 '23 at 21:59

0 Answers0