私の質問はViewModel second time returns nullに関連しています。私はサーバに繰り返し呼び出すとobserve
関数でコールバックを取得していません。AndroidViewModel - 監視機能でデータを返さない
@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();
}
}
アクティビティでは、ViewModelには、以下のように定義されている - -
final NetworkInformationViewModel networkInformationViewModel =
ViewModelProviders.of(this, viewModelFactory).get(NetworkInformationViewModel.class);
observeViewModel(networkInformationViewModel);
observeViewModel
機能がViewModel
に観察可能な追加するために使用される以下は、私が使用していたコードです。上記の機能に次の行をコメントアウト
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);
}
}
}
});
}
は、コールバックが毎回来ることができますが、これを行うための適切な方法が存在しなければなりません。
//observeViewModel(networkInformationViewModel);
ご注意: - 私はこれを実現するためにRxJavaの実装を必要としません。
答えを確認しましたか:https://stackoverflow.com/questions/45889604/livedata-is-not-updating-its-value-after-first-call? – NiVeR
@NiVeRそれを試してみて、助けにはならない。 –
observableに追加する方法をコードに追加できますか? – Gautam