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?
Asked
Active
Viewed 302 times
0
-
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 Answers
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
-
Will you give some sample code or project to implement this feature? – Meenakshi Sundaram Dec 03 '19 at 06:45
-
sorry Niyas Api Still call continuously.This code is not working."_homeApiCalled" initialize each time.Any other options? – Meenakshi Sundaram Dec 04 '19 at 04:56
0
private static var _homeApiCalled = false
Use the static keyword and define this variable in the parent

Shredator
- 940
- 3
- 17
- 32

Prateek Patel
- 1
- 1