【发布时间】:2020-03-13 08:14:45
【问题描述】:
活动
public class SplashScreenActivity extends AppCompatActivity {
offerViewModel offerViewModel;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
textView = findViewById(R.id.text);
offerViewModel = ViewModelProviders.of(this).get(offerViewModel.class);
offerViewModel.init();
offerViewModel.getOfferepository().observe(this, offerResponses -> textView.setText(offerResponses.get(0).getMessage()));
}
}
查看模型代码
public class offerViewModel extends ViewModel {
private MutableLiveData<List<offerResponse>> mutableLiveData;
private offerRepository offerRepository;
public void init() {
if (mutableLiveData != null) {
return;
}
offerRepository = offerRepository.getInstance();
mutableLiveData = offerRepository.getOffers("token");
}
public LiveData<List<offerResponse>> getOfferepository() {
return mutableLiveData;
}
}
存储库类
public class offerRepository {
private static offerRepository offerRepository;
OurClient ourClient;
public offerRepository() {
ourClient = connectionBuilder.cteateService(OurClient.class);
}
public synchronized static offerRepository getInstance(){
if (offerRepository == null){
offerRepository = new offerRepository();
}
return offerRepository;
}
public MutableLiveData<List<offerResponse>> getOffers(String api_token){
MutableLiveData<List<offerResponse>> offerData = new MutableLiveData<>();
ourClient.getOffers(api_token).enqueue(new Callback<List<offerResponse>>() {
@Override
public void onResponse(Call<List<offerResponse>> call, Response<List<offerResponse>> response) {
offerData.setValue(response.body());
}
@Override
public void onFailure(Call<List<offerResponse>> call, Throwable t) {
offerData.setValue(null);
}
});
return offerData;
}
}
在我的应用程序中,我使用实时数据、存储库和活动。
Repository -> To Get Data From the Server Live Data -> To Observe Server Data and then Update UI activity - > Get Live Data info and Update UI.I want Whenever Server Change the data Live Data Will Notify it and activity UI will Update. I try this(Bellow code) But Its Not Updating Live While Screen is on. Only onRestart(),onCreate().. the Data is Updating and UI gets Updated otherwise it is not updating. Please Help me Out From This. How I can Show the Live Changing (Server Live Data ).我已经使用 MutableLiveData 数据(请检查我的代码)来获取实时数据结果,但我没有得到实时数据。我知道状态有问题。由于此代码仅适用于 OnResume,因此我只想知道如何观察 onResume 数据。 如果有人能帮我解决这个问题,我会很高兴。
【问题讨论】:
标签: android mvvm android-livedata mutablelivedata