Search code examples
androidkotlinkotlin-coroutinesandroid-jetpack

How to wait to finish task in kotlin


I have a function like this

internal fun handleResponse(items: List<TestItem>? = null) {
    viewModelScope.launch(Dispatchers.IO) {
        val isDataReturned = testItems != null
        if (isDataReturned) {
            dataModelList = getfilterDataList(items).toMutableStateList()
        }
        requestCompleteLiveData.postValue(isDataReturned)
    }
}

I am receiving data through api call so it may be null or empty. After receiving the data I am passing in the function handleResponse to filter data. getfilterDataList() method is very heavy filter processing doing because it has huge data i.e. more than 1000 items and subitems coming from the server.

So I am thinking to improve code

  • if isDataReturned is return false then I'll send the livedata.

  • If isDataReturned is return true then I have to wait until all value collect by the dataModelList.

    var dataModelList = mutableStateListOf<DataModel>()
    

So what is the best way to achieve this?

I can share you my getfilterDataList method but not fully.

fun getfilterDataList(unfilteredList: List<TestItem>): MutableList<DataModel> {
        return unfilteredList
            .asSequence()
            .mapNotNull { it.testData }
            .filterNot { isInvalidTestData(it) }
            .mapIndexed { index, testData ->
                // more code in here
              DataModel()
            }.toMutableList()
}

Solution

  • You can write suspend function which will be simple as:

    suspend fun handleResponse(items: List<String>? = null): List<String> {
        if (items.isNullOrEmpty()) {
            return listOf()
        }
    
        return withContext(Dispatchers.IO) {
            items.map { it + " MODIFIED" }
        }
    }
    

    Now you can call this function from coroutine or from other suspend function to get handle response.