代替MutableLiveData使用的数据类型?

时间:2020-04-15 17:12:51

标签: android android-livedata android-loader

我正尝试使用Google的自动填充Api来显示地址列表。我试图使用ViewModel而不是AsyncTaskLoader将它们保存在MutableLiveData中。问题是我无法清除MutableLiveData,因此与以前的数据相比,每种类型的列表都变得更长。有什么更好的方法呢?在网上搜索,我没有找到更新的文章。谢谢

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);
        }
}

我的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 个答案:

答案 0 :(得分:0)

尝试应用 SingleLiveEvent ,以便一次观察数据发射。

遵循this article,然后用SingleLiveEvent替换您的MutableLiveData。

尝试一下,如果发现任何问题,请添加评论;)