4

I have a method

fun refrehList() {
    viewModelScope.launch {
        myData.value = withContext(Dispatchers.Default) {
            summaryRepository.getSummaries(true)
        }
        allData.value = withContext(Dispatchers.Default) {
            SummaryRepository.getSummaries(false)
        }
    }
}

Is this correct way of using coroutine. Is the DB operation happening in the background scope

png
  • 4,368
  • 7
  • 69
  • 118

2 Answers2

4

If you're using Room, its documentation states the following:

You can add the suspend Kotlin keyword to your DAO methods to make them asynchronous using Kotlin coroutines functionality. This ensures that they cannot be executed on the main thread.

So you will be safe calling your repository inside the viewModelScope without changing context.

You can find that Room's documentation section here.

Glenn Sandoval
  • 3,455
  • 1
  • 14
  • 22
  • I have those methods as @Transaction. So does that mean I can just call them likefun refrehList() { viewModelScope.launch { myData.value = summaryRepository.getSummaries(true) allData.value = SummaryRepository.getSummaries(false) } } – png Apr 17 '20 at 15:13
  • @png Sure, you can see one of the examples in the link I provided is a transaction and it actually states the following: ***This guidance also applies to DAO methods annotated with `@Transaction`. You can use this feature to build suspending database methods out of other DAO methods. These methods then run in a single database transaction.*** – Glenn Sandoval Apr 17 '20 at 22:40
3

Yes this code will run on separate thread but one after another. Also you should be using Dispatchers.IO for database calls instead of Dispatchers.Default See Io vs Default.

viewModelScope.launch {
        myData.value = withContext(Dispatchers.IO) {
           Log.e("thread1", Thread.currentThread().name)
            summaryRepository.getSummaries(true)
        }
         Log.e("thread2", Thread.currentThread().name)
        allData.value = withContext(Dispatchers.IO) {
           Log.e("thread3", Thread.currentThread().name)
            SummaryRepository.getSummaries(false)
        }
    }

This will print something like :-

E/thread: DefaultDispatcher-worker-1
E/thread2: main
E/thread3: DefaultDispatcher-worker-1

If you want to run those co-routine in parallel you can use async-await .

ADM
  • 20,406
  • 11
  • 52
  • 83