Search code examples
kotlinandroid-roomkotlin-coroutines

Insert,delete operations always successful but returns -1,0 values sometimes


if (!listedeBulundu) {
        Log.e("tag","Yerleştirme bloğuna girildi")
        CoroutineScope(Dispatchers.IO).launch {
            val dbInsertDeferred = async(Dispatchers.IO) {
                viewModel.roomRepository.VeritabaninaYerlestir(scp)
            }

            val dbInsert = dbInsertDeferred.await()
            Log.e("tag",dbInsert.toString())
            
            if (dbInsert != -1L) {
                viewModel.roomRepository.VeritabanindanGetir()
                yazdir()
                Log.e("tag", "Yerleştirme işlemi başarılı")
            } else {
                Log.e("tag", "Yerleştirme işlemi başarısız")
            }
        }
        favoriSimgesi = true
    }

Inserting to room database is always successful.But returns -1 sometimes.Deleting from room database also is always successful but returns 0 sometimes.How do i solve this ?


Solution

  • You cannot return the result of the coroutine operation from outside the coroutine. The coroutine itself is asynchronous from the code immediately following it. The only way you could return the result from this function is to make the function a suspend function that calls the code directly instead of launching a coroutine. See this question and answers for more explanation. Basically, your line of code favoriSimgesi = true executes before or in parallel with the code inside your coroutine. The function that launches this coroutine likely returns before the coroutine is finished.

    It is also incorrect to be using async { } inside your coroutine only to await it right away. That's redundant and unnecessary complexity. async is for doing parallel work, which you are not doing since you immediately await the result before doing anything else.

    And as mentioned in the comment on your question, you should not use CoroutineScope().launch. This is like using GlobalScope, and it will lead to memory and resource leaks. In this case I am inferring your code is in an Activity or Fragment, so you should be using lifecycleScope or viewLifecycleOwner.lifecycleScope respectively.