我可以在Room中将@DatabaseView与LiveData一起使用吗?

时间:2019-06-21 20:00:12

标签: android mvvm kotlin android-livedata database-view

如果通过主线程运行查询,则可以正常工作。 如果我尝试使用Livedata POJO获取DatabaseView,则其抛出错误

java.lang.IllegalArgumentException: Cannot add the same observer with different lifecycles
    at androidx.lifecycle.LiveData.observe(LiveData.java:197)
    at MyFragment.onCreateView(MyFragment.kt:45)
    at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2439)
    at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
    at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
    at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
    at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:802)
    at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
    at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
    at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
    at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
    at androidx.fragment.app.FragmentManagerImpl$1.run(FragmentManager.java:733)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7058)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)

DatabaseView类

@DatabaseView("SELECT ss_pack.id as id, ss_pack.title as title, ss_pack.primary_value as primaryValue FROM ss_pack JOIN favourite WHERE favourite.ss_pack_id = ss_pack.id")
data class AllFavourites(
    val id: Int,
    val title: String,
    val primaryValue: String
)

我的道

interface FavouriteDao {
@Query("SELECT * from AllFavourites")
fun getFavorites(): LiveData<List<AllFavourites>>

@Insert
fun insertFav(favourite: Favourite)
}

我的存储库

class MyRepository(val favoriteDao: FavoriteDao, val categoryDao: CategoryDao) {

val favourites: LiveData<List<AllFavourites>> = favoriteDao.getFavorites()
val categories: LiveData<List<Category>> = categoryDao.loadAllCategories()
}

ViewModel

class MyViewModel(application: Application) : AndroidViewModel(application){
private val myRepository: MyRepository
val favourites: LiveData<List<AllFavourites>>

init {
    val favoriteDao = SDatabase.getDatabase(application, viewModelScope).favoriteDao()
    myRepository = myRepository(favoriteDao, categoryDao)
    favourites = passwordRepository.favourites
}
}

当我在片段中调用此观察时抛出错误

viewModel.favourites.observe(this, androidx.lifecycle.Observer { favorites ->
        favorites?.let {
            print("FAVORITE SIZE ${favorites.size}")
        }
    })

告诉我如何将此MVVM模式与LiveData或kotlin协程一起使用DatabaseView。

我需要通过后台线程而不是UI线程从我的片段中打印最喜欢的大小。

1 个答案:

答案 0 :(得分:1)

onCreateView()可以为同一个Fragment实例多次调用(因为将Fragment放回堆栈中时视图会被破坏,但Fragment实例本身会保留在该位置)。

this中使用observe()时,应该始终使用viewLifecycleOwner而不是onCreateView(),因为这样可以确保先前的观察者(与上次致电onCreateView()的时间已被正确清理:

viewModel.favourites.observe(viewLifecycleOwner, androidx.lifecycle.Observer { favorites ->
    favorites?.let {
        print("FAVORITE SIZE ${favorites.size}")
    }
})