Search code examples
androidviewmodelandroid-architecture-componentsandroid-livedata

Why onChange() called twice when fragment recreated


I'm trying to use the new android architectural components, but I am confused one moment.

I created a ViewModel class

public class BuyViewModel extends ViewModel {

private BuyRepository buyRepository;
private LiveData<Adverts> advertsLiveData;
private boolean isLoading;
private int currentPage;

@Inject
public BuyViewModel(BuyRepository buyRepository) {
    this.buyRepository = buyRepository;
}

public void init(int currentPage) {
    this.currentPage = currentPage;
    if (this.advertsLiveData != null) {
        return;
    }
    Timber.tag("logi").d("BuyViewModel > init -> ");
    advertsLiveData = buyRepository.getAdverts(currentPage);
}

public LiveData<Adverts> getAdvertsLiveData() {
    return advertsLiveData;
}
}

Observe LiveData in my LifeCycleFragment

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    buyViewModel = ViewModelProviders.of(this, viewModelFactory).get(BuyViewModel.class);
    buyViewModel.init(1);
    buyViewModel.getAdvertsLiveData().observe(this, adverts -> {
        Timber.tag("logi").d("BuyFragment > onActivityCreated -> ");
        assert adverts != null;
        adapter.addMoreAdverts(adverts.getResults());
    });

    setupViews();
}

But when I replaced this Fragment with another and switched back to this Fragment, the method onChange was called twice and added two portions of the same data in rvAdapter.


Solution

  • I SOLVED THIS!!! When I creating my ViewModel class, I pass "this" 1-st parameter into method

    buyViewModel = ViewModelProviders.of(**this**, viewModelFactory).get(BuyViewModel.class);

    But I need pass "getActivity()", and code looks like that

    buyViewModel = ViewModelProviders.of(**getActivity()**,viewModelFactory).get(BuyViewModel.class);