Meine Frage bezieht sich auf ViewModel second time returns null wobei ich keinen Rückruf in observe
Funktion bekomme, wenn ich einen wiederholten Anruf zum Server mache. Im Anschluss ist der Code ich verwende -AndroidViewModel - Doppelte Aufrufe gibt keine Daten in der Funktion beobachten zurück
@Singleton
public class NetworkInformationViewModel extends AndroidViewModel {
private LiveData<Resource<NetworkInformation>> networkInfoObservable;
private final APIClient apiClient;
@Inject
NetworkInformationViewModel(@NonNull APIClient apiClient, @NonNull Application application) {
super(application);
this.apiClient = apiClient;
getNetworkInformation();
}
public LiveData<Resource<NetworkInformation>> getNetworkInfoObservable() {
return networkInfoObservable;
}
// making API calls and adding it to Observable
public void getNetworkInformation() {
networkInfoObservable = apiClient.getNetworkInformation();
}
}
In Aktivität wird das Ansichtsmodell wie folgt definiert -
final NetworkInformationViewModel networkInformationViewModel =
ViewModelProviders.of(this, viewModelFactory).get(NetworkInformationViewModel.class);
observeViewModel(networkInformationViewModel);
Die observeViewModel
Funktion verwendet wird, auf ViewModel
beobachtbaren hinzuzufügen.
public void observeViewModel(final NetworkInformationViewModel networkInformationViewModel) {
networkInformationViewModel.getNetworkInfoObservable()
.observe(this, networkInformationResource -> {
if (networkInformationResource != null) {
if (networkInformationResource.status == APIClientStatus.Status.SUCCESS) {
Timber.d("Got network information data");
} else {
final Throwable throwable = networkInformationResource.throwable;
if (throwable instanceof SocketTimeoutException) {
final NetworkInformation networkInformation = networkInformationResource.data;
String error = null;
if (networkInformation != null) {
error = TextUtils.isEmpty(networkInformation.error) ? networkInformation.reply : networkInformation.error;
}
Timber.e("Timeout error occurred %s %s", networkInformationResource.message, error);
} else {
Timber.e("Error occurred %s", networkInformationResource.message);
}
if (count != 4) {
networkInformationViewModel.getNetworkInformation();
count++;
// Uncommenting following line enables callback to be received every time
//observeViewModel(networkInformationViewModel);
}
}
}
});
}
die folgende Zeile in obiger Funktion uncommenting ermöglicht es der Rückruf jedes Mal zu kommen, aber es muss eine richtige Art und Weise, dies zu tun sein.
//observeViewModel(networkInformationViewModel);
Bitte beachten Sie: - Ich brauche nicht RxJava Umsetzung dieses für die Umsetzung.
Haben Sie die Antwort überprüft: https://stackoverflow.com/questions/45889604/livedata-is-not-updating-its-value-after-first-call? – NiVeR
@NiVeR Versuchte das, hilft nicht. –
können Sie Code hinzufügen, wie Sie es beobachtbar hinzufügen? – Gautam