Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 853
kovac777 Avatar asked Oct 16 '25 13:10

kovac777


1 Answers

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

like image 109
kovac777 Avatar answered Oct 19 '25 04:10

kovac777