0

I had used navigation graph in my android project.In my project contains 3 fragments Registration,Login and Home Fragment in Bottom Navigation View.In Home Fragment calls api to fetch list of records.When I navigate that Fragment each time ,it calls api.I want to call that api once when it navigate at first.After close and reopen the app it calls api.How to achieve this functionality using navigation graph with MVVM Architecture?

  • Are you creating ViewModel using ViewModelProvider or lazily creating ViewModel using kotlin KTX library. If you use lazy creating your issue might be resolved. Possibly post the snippet of viewModel creation and calling place of homeApi method. – Raghul Vaikundam Dec 26 '19 at 17:03

2 Answers2

0

Keep one ViewMedel for 3 fragments and stores the response in ViewMedel and keep a flag like given below.

    class MainViewModel : ViewModel() {

    private var _homeApiCalled= false

    fun homeApi(){
        if(!_homeApiCalled){
            //call api here
            _homeApiCalled=true
        }
      }
    }

And call the homeApi() from fragment.

Niyas
  • 717
  • 11
  • 18
0
private static var _homeApiCalled = false

Use the static keyword and define this variable in the parent

Shredator
  • 940
  • 3
  • 17
  • 32