0

The following Kotlin/Room database code runs fine, but I need to get off the main thread.

I've read all kinds of complex tutorials, but just a simple example (if that's possible) would really help!

@Composable
fun myApp(myContext: Context) {

    val db = Room.databaseBuilder (
        myContext,
        AppDatabase::class.java,
        "test.db")
        .allowMainThreadQueries()              // How to eliminate this line?
        .createFromAsset("test.db")
        .build()

    val itemDAO = db.itemDAO()

    var itemList = remember { mutableStateListOf( itemDAO.getAll() ) }
    println("******************** Print Item List ********************")
    for (i in 0 until itemList.size) {
        itemList[i].listIterator().forEach { println(it.first_name + " " + it.last_name) }
    }

}
2
  • 1
    Anything related to data should be handled at the data layer instead of the view layer. Use ViewModel to handle Room data fetching, and use coroutines with Dispatcher.IO to move database operation off the main thread. Commented Apr 2, 2022 at 19:17
  • 1
    Refer docs for more info and sample codebase - developer.android.com/training/data-storage/… Commented Apr 2, 2022 at 19:18

1 Answer 1

0

If you want to move to your db operations to data layer, you should do it in a Repository or even better in a UseCase/Interactor. ViewModel is not data layer but presentation layer, at ViewModel level your data should be already UI representation data that only stores ui related properties.

If you want to use coroutines, mark your functions with suspend keyword so they will do the db operations in Room's own thread. And you will need to call it inside a scope regardless since they will be suspending functions.

    viewModelScope.launch {
        try {
              val itemDAO = db.itemDAO()
              val items = itemDAO.getAll() 
             // You can update value of MutableState with these items

        } catch (e: Exception) {
            
        }
    }
}
Sign up to request clarification or add additional context in comments.

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.