Issue
I am migrating code from AsyncTask to Coroutines because AsyncTask is deprecated. How can I implement the change from AsyncTask to Coroutines in the BookRepository.kt. How can I restructure the code?
package com.room.ps.bookkeeper
import android.app.Application
import androidx.lifecycle.LiveData
import android.os.AsyncTask
import androidx.room.*
import java.util.concurrent.Executors
class BookRepository(application: Application) {
val allBooks: LiveData<List<Book>>
private val bookDao: BookDao
init {
val bookDb = BookRoomDatabase.getDatabase(application)
bookDao = bookDb!!.bookDao()
allBooks = bookDao.allBooks
}
fun getBooksByBookOrAuthor(searchQuery: String): LiveData<List<Book>>? {
return bookDao.getBooksByBookOrAuthor(searchQuery)
}
suspend fun insert(book: Book) {
InsertAsyncTask(bookDao).execute(book)
}
suspend fun update(book: Book) {
UpdateAsyncTask(bookDao).execute(book)
}
suspend fun delete(book: Book) {
DeleteAsyncTask(bookDao).execute(book)
}
companion object {
private class InsertAsyncTask(private val bookDao: BookDao) : AsyncTask<Book, Void, Void>() {
override fun doInBackground(vararg books: Book): Void? {
bookDao.insert(books[0])
return null
}
}
private class UpdateAsyncTask(private val bookDao: BookDao) : AsyncTask<Book, Void, Void>() {
override fun doInBackground(vararg books: Book): Void? {
bookDao.update(books[0])
return null
}
}
private class DeleteAsyncTask(private val bookDao: BookDao) : AsyncTask<Book, Void, Void>() {
override fun doInBackground(vararg books: Book): Void? {
bookDao.delete(books[0])
return null
}
}
}
}
Solution
If Dao operations are suspend
you can just call them:
suspend fun insert(book: Book) {
bookDao.insert(book)
}
// the same for other methods
If Dao operations are not suspend
you need to switch coroutine's context to background thread using withContext(Dispatchers.IO)
function:
private suspend insertBook(book: Book) = withContext(Dispatchers.IO) {
bookDao.insert(book)
}
suspend fun insert(book: Book) {
insertBook(book)
}
// the same for other methods
Answered By - Sergio
Answer Checked By - David Goodson (JavaFixing Volunteer)