1.本地數據源
/**
* 書籍本地數據源
*/
class BookLocalDataSource private constructor(
private val appExecutors: AppExecutors,
private val bookDao: BookDao
) : BookDataSource {
/**
* 獲取書籍列表
*/
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)
}
}
companion object {
/**
* 書籍本地數據源實例
*/
private var INSTANCE: BookLocalDataSource? = null
/**
* 獲取書籍本地數據源實例
*/
@JvmStatic
@Synchronized
fun getInstance(): BookLocalDataSource {
if (INSTANCE == null) {
val bookDao = AppDatabase.getDatabase(MyApplication.context).bookDao()
INSTANCE = BookLocalDataSource(AppExecutors(), bookDao)
}
return INSTANCE!!
}
}
}
2.遠程數據源
class BookRemoteDataSource private constructor(
private val bookService: BookService
) : BookDataSource {
/**
* 獲取書籍列表
*/
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)
}
})
}
companion object {
/**
* 書籍遠程數據源實例
*/
private var INSTANCE: BookRemoteDataSource? = null
/**
* 獲取書籍遠程數據源實例
*/
@JvmStatic
@Synchronized
fun getInstance(): BookRemoteDataSource {
if (INSTANCE == null) {
INSTANCE = BookRemoteDataSource(
ServiceCreator.create<BookService>()
)
}
return INSTANCE!!
}
}
}