【发布时间】:2019-11-14 13:29:59
【问题描述】:
我有以下代码,我正在尝试使用 NyTimes/Store 库从 API 端点获取数据来缓存它
我正在使用 DI 来加载我的依赖项,如下所示
val appModule = module(override = true) {
single<MyAppDatabase> {
Room.databaseBuilder(androidApplication(), MyAppDatabase::class.java, "MJiraniRoomDB")
.fallbackToDestructiveMigration()
.build()
}
//DATABASE ACCESS OBJECTS
factory<BlogDao> { get<MyAppDatabase>().blogDao() }
factory<BlogLocalService> { BlogLocalService(get()) }
factory<BlogRemoteService> { BlogRemoteService(get()) }
factory<BlogStore> { BlogStore(get(), get()) }
我在 RoomStore 中使用 Store 库的服务在这里
package com.example.myapplication.service.BlogService
import com.example.myapplication.model.Blog
import com.nytimes.android.external.store3.base.Fetcher
import com.nytimes.android.external.store3.base.impl.BarCode
import com.nytimes.android.external.store3.base.impl.MemoryPolicy
import com.nytimes.android.external.store3.base.impl.StalePolicy
import com.nytimes.android.external.store3.base.impl.room.StoreRoom
import com.nytimes.android.external.store3.base.room.RoomPersister
import io.reactivex.Observable
import java.util.concurrent.TimeUnit
class BlogStore(val blogRemoteService: BlogRemoteService, val blogLocalService: BlogLocalService) {
var fetcher = Fetcher<List<Blog>, BarCode> {
blogRemoteService.fetchBlogs()
}
val persister = object : RoomPersister<List<Blog>, List<Blog>, BarCode> {
override fun read(barCode: BarCode): Observable<List<Blog>> {
return blogLocalService.fetchAll().toObservable()
}
override fun write(barCode: BarCode, blogList: List<Blog>) {
blogLocalService.addBlogs(blogList)
}
}
var memoryPolicy: MemoryPolicy = MemoryPolicy
.builder()
.setExpireAfterWrite(5)
.setExpireAfterTimeUnit(TimeUnit.SECONDS)
.build()
var store = StoreRoom.from(fetcher, persister, StalePolicy.REFRESH_ON_STALE, memoryPolicy)
fun getBlogs(): Observable<List<Blog>> {
store.clear()
return store.fetch(BarCode.empty())
}
}
我将数据拉到我的 Recyclerview 如下
class RemotePostsFragment : Fragment() {
val scopeProvider by lazy { AndroidLifecycleScopeProvider.from(this) }
val myBlogStore: BlogStore by inject()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
var mRecyclerview = view.findViewById<RecyclerView>(R.id.myRemoteViewRecycler)
var theAdapter = MyAdapter()
myBlogStore.getBlogs()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.autoDisposable(scopeProvider)
.subscribe({ bloglist ->
theAdapter.blogItems = bloglist
}, {
Log.e("RemotePostFragment", "failed got message ${it.message}")
})
mRecyclerview.adapter = theAdapter
mRecyclerview.layoutManager = LinearLayoutManager(this.context)
}
问题是我只从 android room db 加载数据,但从未从服务器获取数据。当我从提取器使用的服务器执行原始查询时,我可以获得博客列表。但是当我在 Fetcher 中使用它时,我无法自动同步。
我的 blogRemoteService 在单独测试时正确返回 Single>。我可能做错了什么?
【问题讨论】:
-
您永远不会从服务器获取,因为您的代码中没有单个 htto 请求,您实际上是在对设备数据库进行事务处理,而不是从 HTTP REST API 请求它
标签: android kotlin store android-room