当数据从API插入数据库并在读取数据库后读取时显示,但不显示任何运行时

时间:2019-08-07 03:51:24

标签: android kotlin rx-java android-room

当数据从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)

0 个答案:

没有答案