我正在尝试使用mvvm架构编写应用程序。但是,当我将数据插入数据库时,在onChange上没有收到任何更改。我要实现的逻辑:转到缓存,获取数据。然后,我们转到服务器并接收数据。如果有更改,请同时更新缓存和ui。告诉我我在做什么错了吗?
class PageFragment : BaseFragment() {
private val pageName= "fly"
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
...
val viewModel = ViewModelProviders.of(this).get(PageViewModel(activity!!.appliacation)::class.java)
viewModel.getPages().observe(this, Observer<Page> { page ->
adapter.contents = page!!.content
})
viewModel.pageName = pageName
return view
}
}
ViewModel类
class PageViewModel constructor(application: Application) : AndroidViewModel(application) {
private var repository: Repository = Repository(application)
private var mutablePages = MutableLiveData<Page>()
fun getPages(): LiveData<Page> = mutablePages
var pageName: String = ""
set(value) {
field = value
loadData(value)
}
private fun loadData(pageName: String) {
GlobalScope.launch {
withContext(Dispatchers.Main) {
mutablePages.value = repository.getPage(pageName)
}
}
}
}
存储库类
class Repository(context: Context) {
private var dbRepository: DbRepository = DbRepository(context)
....
suspend fun getPage(pageName: String): Page =
dbRepository.getPage(pageName).let { pagesMapper.dbToBusinessEntity(it) }.also {
//get data from the server and put it into db
//data from the server put into db successful. By this I will not write how I do it.
GlobalScope.launch { updatePage(pageName) }
}
....
}
DbRepository类
class DbRepository(context: Context) {
private var pagesDao: pagesDao = AppDatabase.getInstance(context).pagesDao()
....
suspend fun getpage(pageName: String): PageDb =
GlobalScope.async { pagesDao.getPage(pageName) }.await()
....
}
道课
@Dao
interface PagesDao {
@Query("SELECT * FROM pages WHERE pageName= :pageName")
fun getPage(pageName: String): PageDb
}
实体数据类
@Entity(tableName = "pages")
data class PageDb(
var content: List<Any>,
@PrimaryKey(autoGenerate = false)
var pageName: String
)
我也想听听对此守则的批评。谢谢!
答案 0 :(得分:0)
发现问题出在哪里... 为了通知LiveData数据更改,从数据库中检索数据的方法不应具有suspend关键字。