data type to use instead of MutableLiveData?

260 views Asked by At

Im trying to show a costumed list of addresses using google's place AutoComplete Api. I tried to save them in a MutableLiveData using ViewModel instead of AsyncTaskLoader. The problem is I cant clear the MutableLiveData so the list gets longer every type with previous data. What would be a better way doing it? searching the web I didnt find an updated article. thanks

MainActivity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

PlacePredictionModelFactory factory =  new PlacePredictionModelFactory(getApplication());
PlacePredictionViewModel  placePredictionModel = ViewModelProviders.of(this,factory).get(PlacePredictionViewModel.class);

final Observer<ArrayList<Address>> placesObserver = places ->{
        // Update the UI
        addressesList = places;
        //Adapter to adapt addresses onto AutoCompleteTextView
        AddressAdapter addressAdapter = new AddressAdapter(getApplicationContext(),addressesList);
        addressEditText.setAdapter(addressAdapter);
        addressEditText.showDropDown();
    };

mAutoCompleteEditText.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            // Observe the LiveData
            placePredictionModel.getPredictedPlaces()
                                .observe(MainActivity.this, placesObserver);
        }
}

my ViewModel:

class PlacePredictionViewModel extends ViewModel {
private SingleLiveEvent<ArrayList<Address>> placesSingleEvent;

 PlacePredictionViewModel(Application application){
    application = application;
    Context context = application.getApplicationContext();

    // Initialize the SDK
    Places.initialize(context, PLACES_KEY);
    // Create a new Places client instance
    placesClient = Places.createClient(context);
  }

 LiveData<ArrayList<Address>> getPredictedPlaces() {
    if (placesSingleEvent == null) { placesSingleEvent = new SingleLiveEvent<>(); }
    //my function to load the predicredplaces
    loadPlacesfromIDs();
    return placesSingleEvent;
  }

  loadPlacesfromIDs(){
   placesClient.fetchPlace(fetchRequest).addOnSuccessListener((fetchResponse) -> {
   //make operatoins to load the data then setValues
   placesSingleEvent.setValue(addressArray);});
   }
}
1

There are 1 answers

1
MustafaKhaled On

Try to apply SingleLiveEvent to be able to observe once for your data emission.

follow this article and replace your MutableLiveData with SingleLiveEvent.

Give it a try and if you find any problem kindly add a comment ;)