Glide 라이브러리 사용 시 Lifecycle

홍성덕·2024년 7월 17일

안드로이드에는 많은 이미지 라이브러리가 있는데 그 중 Glide를 사용할 때 주의할 점에 대해 알게 된 부분이 있어서 글을 남긴다.

Glide.with(binding.imageViewThumbnail.context)
    .load(data.thumbnailUrl)
    .into(binding.imageViewThumbnail)

코드 수정 전에 with함수에 argument로 View의 context를 넣어주었다. 내가 사용한 binding.imageViewThumbnailSearchFragment, FavoriteFragment에 포함되어 있고, 이 두 개의 Fragment는 MainActivity에 호스팅 되어있다. 그래서 ActivityContext가 들어가게 될 것이다.

그런데 context를 사용한 with 함수의 설명을 보면 이런 설명이 나와있다.

  /**
   * Begin a load with Glide by passing in a context.
   *
   * <p>Any requests started using a context will only have the application level options applied
   * and will not be started or stopped based on lifecycle events.
   * 
   * (...생략...)
   *
   * <p>This method is appropriate for resources that will be used outside of the normal fragment or
   * activity lifecycle (For example in services, or for notification thumbnails).
   *
   */
  @NonNull
  public static RequestManager with(@NonNull Context context) {
    return getRetriever(context).get(context);
  }

간략하게 해석하면, lifecycle 이벤트에 따라서 시작되거나 중지되지 않는다는 것이다. 내가 생각한 의도와는 다르게 lifecycle 이벤트에 따라서 작동하지 않는다면, Fragment가 파괴되었음에도 불구하고 Glide가 이미지를 계속 로드하려고 시도하는 불필요한 작업이 발생할 수 있다.

추가로 이 메소드는 Fragment 또는 Activity lifecycle 외부에서 사용되는 리소스에 적합하다고 설명이 나와있다. (예를 들어 서비스, 혹은 Notification 썸네일)

Glide.with(binding.imageViewThumbnail)
    .load(data.thumbnailUrl)
    .into(binding.imageViewThumbnail)

그래서 코드를 위와 같이 context를 넣지 않고 View 자체를 넣어주는 다른 with() 함수를 사용하는 걸로 수정하였다.

  /**
   * Begin a load with Glide that will be tied to the lifecycle of the Fragment, android.app.Fragment, or Activity that contains the View.
   *
   * (...생략...)
   *
   */
  @NonNull
  public static RequestManager with(@NonNull View view) {
    return getRetriever(view.getContext()).get(view);
  }

해당 with()함수의 설명을 보면 이미지 로드를 Fragment, Activity의 lifecycle에 맞춰서 로드를 시작한다고 설명되어 있다.


이번 수정을 통해서 사소한 코드도 잘못 작성하면 완전히 다른 결과로 이어질 수 있다는 것과, 라이브러리의 주석 설명과 내부 코드도 잘 살펴봐야 한다는 것을 다시 한번 깨닫게 되었다.

profile
안드로이드 주니어 개발자

0개의 댓글