0

I'm using a MapView to show some markers based on current user location or a selected map position. The problem is when I navigate to another fragment using navigation component and back. Some steps below fires the livedata value twice.

The loading flow is like below:

Step 1: MapView State - when map is ready(getMapAsync), continue with step 2.

Step 2: Permission State - Check for Location permission and GPS settings. If permission is not granted, requested permission. If permission is granted and gps is available, Livedata fires true, otherwise false.

Step 3: Location Update State - If permission state is true, then requestLocationUpdates from fusedLocationProvider and load data from server. If false, set a predefined position on the map and load data from server for this position.

The problem:

Initially it works well. Step 1 - 3 firing once. When I navigate to another fragment and back, Step 1 - 3 firing the last value which contains also the data from initial load. But in step 1, I'm checking always for permission which returns true or false again. This causes step 2 and 3 to loading again, which leads to load data from server again.

I can check for permission in onCreate but step 1 (MapView) has to be ready before Step 2.

Any idea how to prevent loading data from server again. I've tried SingleEvent (https://proandroiddev.com/singleliveevent-to-help-you-work-with-livedata-and-events-5ac519989c70) for step one. This works well but I need the mapview state firing again to display some buttons based on the mapview state.

Note: viewmodel constains every livedata object and is an activityViewModel. Every step has it's own live data object.

Erkan
  • 140
  • 2
  • 11

1 Answers1

0

I found a solution now:

The position LatLng is the key for loading data from server. Every time when a new position is arrived from location provider, the method for loading data from server is called again.

The solution is to load the data only when the position has changed. This prevents the loading data from server again and the last value from livedata will be applied.

This causes a problem with the initial load. Initially, the position I stored and the position which the location provider returns are the same when GPS is not available or permission is not granted. Therefore it was necessary to check if the fragment is called for the first time. If true, load the data even if the position are the same.

Erkan
  • 140
  • 2
  • 11