1.本地?cái)?shù)據(jù)源
/**
* 書籍本地?cái)?shù)據(jù)源
*/
object BookLocalDataSource : BookDataSource {
private val appExecutors: AppExecutors = AppExecutors()
private val bookDao: BookDao = AppDatabase.getDatabase(MyApplication.context).bookDao()
/**
* 獲取書籍列表
*/
override fun getBooks(callback: CommonCallback<List<Book>>) {
appExecutors.diskIO.execute {
callback.onSuccess(bookDao.getBooks())
}
}
/**
* 更新書籍
*/
override fun updateBook(book: Book, callback: CommonCallback<Book>) {
appExecutors.diskIO.execute {
bookDao.updateBook(book)
callback.onSuccess(book)
}
}
/**
* 刪除所有書籍
*/
fun deleteAllBook(callback: CommonCallback<Boolean>) {
appExecutors.diskIO.execute {
bookDao.deleteAllBook()
callback.onSuccess(true)
}
}
}
2.遠(yuǎn)程數(shù)據(jù)源
/**
* 書籍遠(yuǎn)程數(shù)據(jù)源
*/
object BookRemoteDataSource : BookDataSource {
/**
* 書籍服務(wù)
*/
private val bookService: BookService = ServiceCreator.create<BookService>()
/**
* 獲取書籍列表
*/
override fun getBooks(callback: CommonCallback<List<Book>>) {
bookService.getBooks().enqueue(object : Callback<Result<List<Book>>> {
override fun onResponse(
call: Call<Result<List<Book>>>,
response: Response<Result<List<Book>>>
) {
response.body()?.also {
if (it.status == 0) {
callback.onSuccess(it.data)
} else {
callback.onFailure(R.string.error_net)
}
}
}
override fun onFailure(call: Call<Result<List<Book>>>, t: Throwable) {
callback.onFailure(R.string.error_net)
}
})
}
/**
* 更新書籍
*/
override fun updateBook(book: Book, callback: CommonCallback<Book>) {
bookService.updateBook(book.id, book).enqueue(object : Callback<Result<Book>> {
override fun onResponse(call: Call<Result<Book>>, response: Response<Result<Book>>) {
response.body()?.also {
if (it.status == 0) {
callback.onSuccess(it.data)
} else {
callback.onFailure(R.string.error_net)
}
}
}
override fun onFailure(call: Call<Result<Book>>, t: Throwable) {
callback.onFailure(R.string.error_net)
}
})
}
}