【问题标题】:What do I supply to "LifeCycleOwner" parameter on observe in Kotlin?在 Kotlin 中观察时,我应该向“LifeCycleOwner”参数提供什么?
【发布时间】:2020-07-02 11:41:58
【问题描述】:

我是 Android Room 的新手,它使用我也不熟悉的 LiveData。我注意到在教程中,返回的数据使用LiveData 包装器,如下所示:

@Dao
interface PersonDao {
    @Query("SELECT * FROM person")
    fun getAll(): LiveData<List<Person>>
}

然后读取数据,我使用这个代码:

class PersonListActivity: AppCompatActivity() {

    List<Person> personList = listOf()

    init {
        val db = RoomDatabase.getDatabaseInstance()
        db.personDao.getAll().observe(this, Observe<List<Person>> { data ->
            personList = data
        })
    }

}

问题是 IDE 引发错误“类型不匹配”。必需:LifeCycleOwner。找到:PersonListActivity。我不明白教程如何随便将“this”提供给观察所有者参数。我还尝试将contextapplicationContext 提供给所有者参数,但它不起作用。

检查LifeCycleOwner 类后,我尝试添加 LifeCycleOwner 实现。但是该类需要实现getLifeCycle() 函数。所以我回到了零。

class PersonListActivity: AppCompatActivity(), LifeCycleOwner {

    List<Person> personList = listOf()

    init {
        val db = RoomDatabase.getDatabaseInstance()
        db.personDao.getAll().observe(this, Observe<List<Person>> { data ->
            personList = data
        })
    }

    override fun getLifeCycle() {
        // what should I return here??????
    }

}

为什么我读过的所有关于 LiveData 的教程都没有提到关于 LifeCycleOwner 的任何内容?我在这里使用了错误的观察功能吗?

public abstract class LiveData<T> {
    ...
    @MainThread
    public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) { ... }
    ...
}

【问题讨论】:

  • 你使用的是什么版本的androidx.appcompat:appcompat

标签: android android-livedata observer-pattern


【解决方案1】:

自从androidx.appcompat:appcompat的版本1.1.0(不包括不稳定版本),AppCompatActivity实现LifecycleOwner(见ComponentActivity)。所以调用时可以使用this

db.personDao.getAll().observe(this, Observe<List<Person>> { data ->
    personList = data
})

没有实现其他任何东西。

此外,我会将这些行移至Activity.onCreate()

【讨论】:

  • 你是对的。我的 appcompat 不在 1.1.0 版上。我把它改成1.1.0后,错误就消失了。谢谢!
猜你喜欢
  • 1970-01-01
  • 2020-10-07
  • 1970-01-01
  • 2012-10-06
  • 2013-01-02
  • 2011-02-08
  • 1970-01-01
  • 2010-11-02
  • 2018-07-01
相关资源
最近更新 更多