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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 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.
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 .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.