当数据从API获取到插入数据库时,并在读取数据库后读取,但是没有显示任何运行时运行的应用程序
RemoteDataStore
interface RemoteDataStore {
@Headers("Content-Type: application/json")
@GET("api/products")
fun getProductRemote(): Flowable<List<Product>>
}
productDao.kt
@Dao
interface ProductDao {
@Query("SELECT * FROM products")
fun getProduct():Single<List<Product>>
@Insert
fun insertAll(products: List<Product>):List<Long>
}
RemoteRepositoryPattern
class RemoteRepositoryPattern(val api: RemoteDataStore, val db: AppDatabase) : Repository {
override fun getProductResultsFromNetwork(): Flowable<List<Product>> {
return api.getProductRemote().doOnNext {
db.productDao().insertAll(it)
}
}
override fun getProductResultsFromDatabase(): Flowable<List<Product>> {
return db.productDao().getProduct()
}
override fun getProductResults(): Flowable<List<Product>> {
return getProductResultsFromDatabase()
.filter { a->
a.isNotEmpty()
}
.switchIfEmpty {
Flowable.defer { getProductResultsFromNetwork() }
}
}
}
MainViewmodel.kt
class MainViewModel(private val remoteRepositoryPattern: RemoteRepositoryPattern) : ViewModel() {
fun getProduct() = remoteRepositoryPattern.getProductResults()
}
MainActivity.kt
fun init() {
mainViewmodel.getProduct().subscribe {
val adapter = ProductAdapter(it)
RecyclerView2.layoutManager = LinearLayoutManager(this, LinearLayout.HORIZONTAL, false)
RecyclerView2.adapter = adapter
adapter.update(it)
}.addTo(this.CompositeDisposable)