Search code examples
kotlinandroid-roomkotlin-coroutines

Why method not return anything after dao method?


My code stop working after call dao method, if I use GlobalScope code working, but then LiveData not update changes

override suspend fun addNewTask(title: String,priority : Int,date: Date): Boolean {
    var isSuccess = false

    val newTask = hashMapOf(
        "title" to title,
        "priority" to priority,
        "task_points" to converterListOfListToJson(listOf()),
        "date" to Timestamp(date)
    )

    val user: User? = userDao.getCurrentUser()
    val newTaskList = user?.tasks?.toMutableList()
    val generatedDoc = db.collection(CollectionNames.tasks).document()
    val userTasks = db.collection(CollectionNames.users).document(user!!.id)

    generatedDoc.set(newTask)
        .addOnSuccessListener { isSuccess = true }
        .addOnFailureListener { Log.e(TAG, "Error writing document") }.await()

    userTasks.update(
        "tasks", FieldValue.arrayUnion(generatedDoc.id)
    ).await()

    newTaskList?.add(generatedDoc.id)
    
    taskDao.insert(Task(generatedDoc.id, title, date, listOf(), priority.toLong())) //after code out

    user.tasks = newTaskList!!.toList()

    userDao.updateUser(user)

    return isSuccess
}

This call of this method, addNewTask full complete but after code just end method

fun createTask(title : String, priority : String,date: Date) {
    viewModelScope.launch{
        tasksUseCase.addNewTask(title, priority, date)
        tasksUseCase.updateTaskFromLocalDB().collect { //it is not called
            _taskList.postValue(it)
        }

    }
}

In DAO I just use annotation update and insert

@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(task: Task)

My function call in dialog fragment on click, but with viewModel of parent fragment, function deadlock without errors


Solution

  • The problem was that the viewModel was a DialogFragment which was destroyed after the method was called, due to which the ViewModelScope also ceased to exist and the method crashed in the middle