Reputation: 7866
I want to create a utility class that will manage my Room database. Using live data, I am able to observe changes within my database, however, I can only place this observer in my Activity class. I want to confirm that this is really the case. I have tried to use both a context and Activity as a perimeter.
I have also added the following library to gradle
implementation "android.arch.lifecycle:extensions:1.1.1"
Here is an example of how I use the observer
public DatabaseUtils(AppDatabase db, Context context) {
db.testDao().getAllLiveList().observe(
context, new Observer<List<TestEntity>>() {
@Override
public void onChanged(@Nullable List<TestEntity> testEntities) {
// do work
}
});
}
This works fine in an Activity, but moved to a class that does not extend Activity I am receiving the error :
Wrong 1st argument. Found....required: 'android.arch.lifecycle.LifecycleOwner error
Upvotes: 1
Views: 2820
Reputation: 3894
That's because LiveData.observe takes LifecycleOwner
as its first argument and not a Context
, and an activity is also a LifecycleOwner
:
public class SupportActivity extends Activity implements LifecycleOwner {
// Your activity may be a subclass of this activity.
}
So you probably want to pass a LifecycleOwner
instead of a Context
to your DatabaseUtil
. Or you can use LiveData.observeForever if you do not care about the lifecycle.
Upvotes: 6