Skip to content Skip to sidebar Skip to footer

Android Mvvm Livedata Not Observing

This is my first time using MVVM architecture.I am also using LiveData. I simply retrieve data from server using Retrofit.So upon clicking a button in the View(MainActivity.class)

Solution 1:

You're creating a new ViewModel in the RetrofitHandler, so nothing is observing that viewmodel. Instead of having the RetrofitHandler rely on a ViewModel internally, it's probably safer to handle the Retrofit callback inself, and post data there.

publicvoidhandleRetrofitcall(){
    retrofitHandler=new RetrofitHandler();
    retrofitHandler.getData(new Callback<List<Unknownapi.Data>> {
         // add actual callback implementation here
    ); // add a callback here, so that the data is available in the view model. Then post the results from here.
}

Edit: More clarification.

In the Activity, you're correctly creating a ViewModel and observing it (we'll call that ViewModel A). ViewModel A is then creating a RetrofitHandler and calling getData on that Retrofithandler. The issue is that RetrofitHandler is creating a new ViewModel in getData (which I'm going to call ViewModel B). The issue is that the results are being posted to ViewModel B, which nothing is observing, so it seems like nothing is working.

Easy way to avoid this issue is to make sure that only an Activity/Fragment is relying on (and creating) ViewModels. Nothing else should know about the ViewModel.

Edit 2: Here's a simple implementation. I haven't tested it, but it should be more or less correct.

// shouldn't know anything about the view model or the viewpublicclassRetrofitHandler { 
    privateApiInterface apiInterface;

    // this should probably pass in a different type of callback that doesn't require retrofitpublicvoidgetData(Callback<Unknownapi> callback) {
        // only create the apiInterface onceif (apiInterface == null) {
            apiInterface = ApiClient.getClient().create(ApiInterface.class);
        }

        // allow the calling function to handle the result
        apiInterface.doGetListResources().enqueue(callback);
    }
}

// shouldn't know how retrofit handler parses the datapublicclassSimpleViewModelextendsViewModel {
    privateRetrofitHandler retrofitHandler = newRetrofitHandler();
    // store data in mutableSize, not with a backing field.privateMutableLiveData<Integer> mutableSize = newMutableLiveData<>();

    publicvoidhandleRetrofitCall() {
        // handle the data parsing here
        retrofitHandler.getData(newCallback<Unknownapi>() {
            @OverridepublicvoidonResponse(Call<Unknownapi> call, Response<Unknownapi> response) {
                Unknownapi unknownapi = response.body();
                int listSize = unknownapi.getData().size;
                // set the value of the LiveData. Observers will be notified
                mutableSize.setValue(listSize); // Note that we're using setValue because retrofit callbacks come back on the main thread.Log.e("Size", Integer.toString(listSize));
            }

            @OverridepublicvoidonFailure(Call<Unknownapi> call, Throwable t) {
                // error handling should be added here
            }
        });
    }

    // this should probably return an immutable copy of the objectpublicMutableLiveData<Integer> getObject() {
        return mutableSize;
    }
}

publicclassMainActivityextendsAppCompatActivity {
    privateTextView status;

    // initialize the view model only onceprivateSimpleViewModel viewModel = ViewModelProviders.of(MainActivity.this).get(SimpleViewModel.class);

    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        status = findViewById(R.id.status);

        // observe the view model's changes
        viewModel.getObject().observe(this, newObserver<Integer>() {
            @OverridepublicvoidonChanged(@Nullable Integer integer) {
                // you should handle possibility of interger being nullLog.e("lk","f");
                status.setText(Integer.toString(integer));

            }
        });

        findViewById(R.id.retrofit).setOnClickListener(newView.OnClickListener() {
            @OverridepublicvoidonClick(View v) {
                // call the view model's function
                viewModel.handleRetrofitCall();
            }
        });

    }
}

Post a Comment for "Android Mvvm Livedata Not Observing"