Why onChange() called twice when fragment recreated

Viewed 2883

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.

2 Answers
Related