我正在学习RxJava和ViewModel。因此,对于我的练习示例,我只想创建一个数据类,使用ViewModel来获取该数据,并实现RxJava。
在我的CustomViewModel
中,我使用以下代码对名称进行了硬编码:
UserModel userModel = new UserModel("ABC");
userModelMutableLiveData.setValue(userModel);
我的主要活动是观察者和可观察者,但是当我只知道使用just()
对发出的数据进行硬编码时,例如just("ABC")
。
我不知道如何从CustomViewModel
发出可观察的呼叫。我的老师告诉我为此做一个 Interface ,但是我对Interface不太满意,我也不知道该怎么做。
谢谢!
这是我的UserModel
数据类
public class UserModel {
private String name;
public UserModel(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
这是我的CustomViewModel
课:
public class CustomViewModel extends ViewModel {
public MutableLiveData<UserModel> userModelMutableLiveData;
public MutableLiveData<UserModel> getUserModelMutableLiveData() {
if(userModelMutableLiveData == null){
userModelMutableLiveData = new MutableLiveData<>();
loadData();
}
return userModelMutableLiveData;
}
private void loadData() {
//I'm trying to make this as simple as I can
UserModel userModel = new UserModel("ABC");
userModelMutableLiveData.setValue(userModel);
}
@Override
protected void onCleared() {
super.onCleared();
}
}
这是我的MainActivity
,在这里我称为 Observer 和 Observable
public class MainActivity extends AppCompatActivity {
private String TAG = "MainActivity";
Disposable disposable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Observable and Observer
Observer<String> namesObserver = getNamesObserver();
Observable<String> namesObservable = getNamesObservable();
//Subscribe step
namesObservable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(namesObserver);
}
//emit data
private Observable<String> getNamesObservable(){
return Observable.just(//I don't know what to do);
}
//observer
private Observer<String> getNamesObserver(){
return new Observer<String>(){
@Override
public void onSubscribe(Disposable disposable) {
//bonding
MainActivity.this.disposable = disposable;
Log.d(TAG, "onSubscribe");
}
@Override
public void onNext(String s) {
Log.d(TAG, "onNext " + s);
}
@Override
public void onError(Throwable e) {
Log.e(TAG, "onError " + e.getMessage());
}
@Override
public void onComplete() {
Log.d(TAG, "onComplete");
}
};
}
@Override
protected void onDestroy() {
super.onDestroy();
disposable.dispose();
}
}