我正在尝试在MainActivity中创建一个ViewModel,它观察某些单例组件中的某些数据变化。目标是在该活动的一些片段中使用该ViewModel。但是到目前为止,即使不涉及片段,它也不起作用。该应用在启动时卡住,无法打印:
java.lang.RuntimeException: Unable to start activity ComponentInfo{my_package.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class my_package.MyViewModel
my_package.App cannot be cast to android.arch.lifecycle.LifecycleOwner
问题似乎出在行中:MyCustomSingletonComponent.getInstance().getSomeDataLiveData().observe......
代码:
public class MyCustomSingletonComponent
{
public MutableLiveData<CustomClass> someData = new MutableLiveData<>();
private static final MyCustomSingletonComponent instance = new MyCustomSingletonComponent();
private MyCustomSingletonComponent() {
someData = new MutableLiveData<>();
}
public static MyCustomSingletonComponent getInstance() {
return instance;
}
public LiveData<CustomClass> getDataLiveData()
{
return someData;
}
}
public class MyViewModel extends AndroidViewModel {
public MyViewModel(@NonNull Application application)
{
super(application);
MyCustomSingletonComponent.getInstance().getSomeDataLiveData().observe(getApplication(), myData -> {
...
});
}
}
public class MainActivity extends AppCompatActivity
{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myViewModel = ViewModelProviders.of(this).get(MyViewModel.class);
....
}
}
答案 0 :(得分:1)
首先,Application
不是LifecycleOwner
,因此您不能将其传递给observe()
上的LiveData
。活动和片段是标准的生命周期所有者。
第二,恕我直言,ViewModel
不应观察任何内容。使用ViewModel
的事物进行观察。 MyViewModel
可能会紧紧抓住LiveData
,但是MainActivity
就是观察到的那个。