androidkotlinkotlin-coroutinesandroid-viewmodelcoroutinescope

Last line of viewModelScope.launch(Dispatchers.IO) coroutine never get executed


I have added some logs to understand the control flow inside a coroutine. When I call the getNode() method of my ViewModel class I can see the logs in the following order-

print 1
print 2
print 5
print 3

Everything looks good till this point but the log to print 3 never get executed. Any idea why the control flow is not reaching the last line of the getNotes() method?

Here is the getNode() method inside ViewModel class-

private fun getNotes() {
    Log.d("","print 1")
    viewModelScope.launch(Dispatchers.IO) {
        Log.d("","print 2")
        getNotesUserCase().collectLatest {
            _notesStateFlow.value = it
            Log.d("","print 3")
        }
        Log.d("","print 4")
    }
}

Here is the GetNotesUserCase class-

class GetNotesUserCase @Inject constructor(private val dataRepository: DataRepository) {
    suspend operator fun invoke(): Flow<List<Note>>  {
        Log.d("","print 5")
        return dataRepository.getNotes().transform { noteEntityList ->
            emit(noteEntityList.map { it.toNote() })
        }
    }
}

Solution

  • I'm guessing dataRepository.getNotes() is a shared flow (or something similar) that never terminates. This means getNotesUserCase() will never terminate which in turn means the collectLatest will never return so this is expected behavior.