【问题标题】:I do not receive changes to onChange when inserting data into the database将数据插入数据库时​​,我没有收到对 onChange 的更改
【发布时间】:2019-05-06 21:53:41
【问题描述】:

我正在尝试使用 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

)

我也想听听对此代码的批评。谢谢!

【问题讨论】:

    标签: android mvvm kotlin android-livedata


    【解决方案1】:

    找到问题所在... 为了让 LiveData 能够收到数据更改的通知,从数据库中检索数据的方法不应该有 suspend 关键字。

    【讨论】:

      猜你喜欢
      • 2017-11-02
      • 1970-01-01
      • 2013-11-23
      • 2017-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-03
      相关资源
      最近更新 更多