Активность
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()));
}
}
ViewModelCode
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 (пожалуйста, проверьте мой код), чтобы получить результат данных Live, но я не получаю данные Live. Я знаю, что есть проблема с государством. так как этот код не работает только OnResume, поэтому я просто хочу знать, как я могу наблюдать данные на OnResume. Я буду рад, если кто-нибудь может помочь мне в этом.