androidmemory-leaksandroid-lifecycleandroid-architecture-componentslifecycleowner

Pass activity to LifecycleObserver


I need to pass activity to a LifecycleObserver class for a location task:

class LocationObserver(
        private val context: Context,
        private val activity: FragmentActivity) : LifecycleObserver {
    
    private var locationClient: FusedLocationProviderClient? = null
    private val locationListener = OnSuccessListener { location: Location? ->
        if (location != null) {
            val lat = location.latitude
            val long = location.longitude
            ...
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun start() {
        locationClient = LocationServices.getFusedLocationProviderClient(activity)
        ...
        locationClient?.lastLocation?.addOnSuccessListener(activity, locationListener)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun stop() {
        locationClient = null
    }
}

The LocationObserver is created and used in the fragment:

public class LocationFragment extends Fragment {
    private LocationObserver locationObserver;
    
    public View onCreateView(@NonNull LayoutInflater inflater,
                       ViewGroup container, Bundle savedInstanceState) {
        ...
        locationObserver = new LocationObserver(this.getContext(), this.getActivity());
        getLifecycle().addObserver(locationObserver);
        
        return root;
    }
    ...
}

The question is: will pass activity to LifecycleObserver-class cause a memory leak? If so, what could be the solution? Thank you so much for any answer/comment!


Solution

  • Well if the fragment lives inside that Activity, probably your Fragment won't have a longer lifecycle, so leaks won't really occur even if you keep references to the activity.

    But as long as you remove all your Activity references in your LocationObserver you can feel pretty safe.