├── app ├── .gitignore ├── src │ ├── main │ │ ├── res │ │ │ ├── values │ │ │ │ ├── strings.xml │ │ │ │ ├── colors.xml │ │ │ │ └── styles.xml │ │ │ ├── mipmap-hdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-mdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xhdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xxhdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xxxhdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-anydpi-v26 │ │ │ │ ├── ic_launcher.xml │ │ │ │ └── ic_launcher_round.xml │ │ │ ├── layout │ │ │ │ ├── fragment_activity_main.xml │ │ │ │ ├── view_holder_main.xml │ │ │ │ └── activity_main.xml │ │ │ ├── drawable-v24 │ │ │ │ └── ic_launcher_foreground.xml │ │ │ └── drawable │ │ │ │ └── ic_launcher_background.xml │ │ ├── java │ │ │ └── com │ │ │ │ └── yfujiki │ │ │ │ └── recyclerviewmemoryleak │ │ │ │ ├── AppState.kt │ │ │ │ ├── MainApp.kt │ │ │ │ ├── MainActivity.kt │ │ │ │ ├── MainActivityFragment.kt │ │ │ │ └── MainRecyclerViewAdapter.kt │ │ └── AndroidManifest.xml │ ├── test │ │ └── java │ │ │ └── com │ │ │ └── yfujiki │ │ │ └── recyclerviewmemoryleak │ │ │ └── ExampleUnitTest.kt │ └── androidTest │ │ └── java │ │ └── com │ │ └── yfujiki │ │ └── recyclerviewmemoryleak │ │ └── ExampleInstrumentedTest.kt ├── proguard-rules.pro └── build.gradle ├── settings.gradle ├── Resources ├── Adapter.png ├── Structure.png ├── RxSubscriber.png ├── Structure-actual.png ├── structure-actual-for-adapter.png ├── Structure-actual-for-view-holder.png ├── structure-after-nullouting-adapter.png └── structure-after-removing-adapter-reference.png ├── docs └── images │ ├── Adapter.png │ ├── Structure.png │ ├── RxSubscriber.png │ ├── Structure-actual.png │ ├── structure-actual-for-adapter.png │ └── Structure-actual-for-view-holder.png ├── .idea ├── dictionaries │ └── yuichi.xml ├── codeStyles │ ├── codeStyleConfig.xml │ └── Project.xml ├── vcs.xml ├── compiler.xml ├── runConfigurations.xml ├── gradle.xml └── misc.xml ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .gitignore ├── gradle.properties ├── gradlew.bat ├── gradlew ├── README-ja.md └── README.md /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app' 2 | -------------------------------------------------------------------------------- /Resources/Adapter.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yfujiki/RecyclerViewMemoryLeak/HEAD/Resources/Adapter.png -------------------------------------------------------------------------------- /Resources/Structure.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yfujiki/RecyclerViewMemoryLeak/HEAD/Resources/Structure.png -------------------------------------------------------------------------------- /docs/images/Adapter.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yfujiki/RecyclerViewMemoryLeak/HEAD/docs/images/Adapter.png -------------------------------------------------------------------------------- /Resources/RxSubscriber.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yfujiki/RecyclerViewMemoryLeak/HEAD/Resources/RxSubscriber.png -------------------------------------------------------------------------------- /docs/images/Structure.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yfujiki/RecyclerViewMemoryLeak/HEAD/docs/images/Structure.png -------------------------------------------------------------------------------- /.idea/dictionaries/yuichi.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /docs/images/RxSubscriber.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yfujiki/RecyclerViewMemoryLeak/HEAD/docs/images/RxSubscriber.png -------------------------------------------------------------------------------- /Resources/Structure-actual.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yfujiki/RecyclerViewMemoryLeak/HEAD/Resources/Structure-actual.png -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | RecyclerViewMemoryLeak 3 | 4 | -------------------------------------------------------------------------------- /docs/images/Structure-actual.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yfujiki/RecyclerViewMemoryLeak/HEAD/docs/images/Structure-actual.png -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yfujiki/RecyclerViewMemoryLeak/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /Resources/structure-actual-for-adapter.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yfujiki/RecyclerViewMemoryLeak/HEAD/Resources/structure-actual-for-adapter.png -------------------------------------------------------------------------------- /Resources/Structure-actual-for-view-holder.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yfujiki/RecyclerViewMemoryLeak/HEAD/Resources/Structure-actual-for-view-holder.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yfujiki/RecyclerViewMemoryLeak/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yfujiki/RecyclerViewMemoryLeak/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yfujiki/RecyclerViewMemoryLeak/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yfujiki/RecyclerViewMemoryLeak/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /docs/images/structure-actual-for-adapter.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yfujiki/RecyclerViewMemoryLeak/HEAD/docs/images/structure-actual-for-adapter.png -------------------------------------------------------------------------------- /Resources/structure-after-nullouting-adapter.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yfujiki/RecyclerViewMemoryLeak/HEAD/Resources/structure-after-nullouting-adapter.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yfujiki/RecyclerViewMemoryLeak/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /docs/images/Structure-actual-for-view-holder.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yfujiki/RecyclerViewMemoryLeak/HEAD/docs/images/Structure-actual-for-view-holder.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yfujiki/RecyclerViewMemoryLeak/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yfujiki/RecyclerViewMemoryLeak/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yfujiki/RecyclerViewMemoryLeak/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yfujiki/RecyclerViewMemoryLeak/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yfujiki/RecyclerViewMemoryLeak/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /Resources/structure-after-removing-adapter-reference.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yfujiki/RecyclerViewMemoryLeak/HEAD/Resources/structure-after-removing-adapter-reference.png -------------------------------------------------------------------------------- /.idea/codeStyles/codeStyleConfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/caches/build_file_checksums.ser 5 | /.idea/libraries 6 | /.idea/modules.xml 7 | /.idea/workspace.xml 8 | .DS_Store 9 | /build 10 | /captures 11 | .externalNativeBuild 12 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #008577 4 | #00574B 5 | #D81B60 6 | 7 | -------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /app/src/main/java/com/yfujiki/recyclerviewmemoryleak/AppState.kt: -------------------------------------------------------------------------------- 1 | package com.yfujiki.recyclerviewmemoryleak 2 | 3 | import io.reactivex.subjects.PublishSubject 4 | 5 | class AppState { 6 | companion object { 7 | val stateSubject: PublishSubject = PublishSubject.create() 8 | } 9 | } -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/test/java/com/yfujiki/recyclerviewmemoryleak/ExampleUnitTest.kt: -------------------------------------------------------------------------------- 1 | package com.yfujiki.recyclerviewmemoryleak 2 | 3 | import org.junit.Test 4 | 5 | import org.junit.Assert.* 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * See [testing documentation](http://d.android.com/tools/testing). 11 | */ 12 | class ExampleUnitTest { 13 | @Test 14 | fun addition_isCorrect() { 15 | assertEquals(4, 2 + 2) 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /app/src/main/res/layout/fragment_activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 10 | -------------------------------------------------------------------------------- /app/src/main/java/com/yfujiki/recyclerviewmemoryleak/MainApp.kt: -------------------------------------------------------------------------------- 1 | package com.yfujiki.recyclerviewmemoryleak 2 | 3 | import android.app.Application 4 | import com.squareup.leakcanary.LeakCanary 5 | 6 | class MainApp: Application() { 7 | override fun onCreate() { 8 | super.onCreate() 9 | if (LeakCanary.isInAnalyzerProcess(this)) { 10 | // This process is dedicated to LeakCanary for heap analysis. 11 | // You should not init your app in this process. 12 | return 13 | } 14 | LeakCanary.install(this) 15 | // Normal app init code... 16 | } 17 | } -------------------------------------------------------------------------------- /.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/main/res/layout/view_holder_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 13 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 17 | 18 | -------------------------------------------------------------------------------- /app/src/main/java/com/yfujiki/recyclerviewmemoryleak/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package com.yfujiki.recyclerviewmemoryleak 2 | 3 | import android.os.Bundle 4 | import androidx.appcompat.app.AppCompatActivity 5 | import io.reactivex.disposables.CompositeDisposable 6 | 7 | class MainActivity : AppCompatActivity() { 8 | val disposable = CompositeDisposable() 9 | 10 | override fun onCreate(savedInstanceState: Bundle?) { 11 | super.onCreate(savedInstanceState) 12 | setContentView(R.layout.activity_main) 13 | } 14 | 15 | override fun onDestroy() { 16 | super.onDestroy() 17 | 18 | if (!disposable.isDisposed) { 19 | disposable.dispose() 20 | } 21 | } 22 | 23 | protected fun finalize() { 24 | println("Activity was reclaimed") 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/yfujiki/recyclerviewmemoryleak/ExampleInstrumentedTest.kt: -------------------------------------------------------------------------------- 1 | package com.yfujiki.recyclerviewmemoryleak 2 | 3 | import android.support.test.InstrumentationRegistry 4 | import android.support.test.runner.AndroidJUnit4 5 | 6 | import org.junit.Test 7 | import org.junit.runner.RunWith 8 | 9 | import org.junit.Assert.* 10 | 11 | /** 12 | * Instrumented test, which will execute on an Android device. 13 | * 14 | * See [testing documentation](http://d.android.com/tools/testing). 15 | */ 16 | @RunWith(AndroidJUnit4::class) 17 | class ExampleInstrumentedTest { 18 | @Test 19 | fun useAppContext() { 20 | // Context of the app under test. 21 | val appContext = InstrumentationRegistry.getTargetContext() 22 | assertEquals("com.yfujiki.recyclerviewmemoryleak", appContext.packageName) 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 17 | 18 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx1536m 10 | # When configured, Gradle will run in incubating parallel mode. 11 | # This option should only be used with decoupled projects. More details, visit 12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 13 | # org.gradle.parallel=true 14 | # Kotlin code style for this project: "official" or "obsolete": 15 | kotlin.code.style=official 16 | 17 | # Androidx 18 | android.useAndroidX=true 19 | android.enableJetifier=true 20 | 21 | -------------------------------------------------------------------------------- /app/src/main/java/com/yfujiki/recyclerviewmemoryleak/MainActivityFragment.kt: -------------------------------------------------------------------------------- 1 | package com.yfujiki.recyclerviewmemoryleak 2 | 3 | import android.os.Bundle 4 | import android.view.LayoutInflater 5 | import android.view.View 6 | import android.view.ViewGroup 7 | import androidx.fragment.app.Fragment 8 | import androidx.recyclerview.widget.LinearLayoutManager 9 | import kotlinx.android.synthetic.main.fragment_activity_main.* 10 | 11 | class MainActivityFragment : Fragment() { 12 | 13 | private lateinit var adapter: MainRecyclerViewAdapter 14 | 15 | override fun onCreate(savedInstanceState: Bundle?) { 16 | super.onCreate(savedInstanceState) 17 | 18 | adapter = MainRecyclerViewAdapter((activity as MainActivity).disposable) 19 | retainInstance = true 20 | } 21 | 22 | override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { 23 | return inflater.inflate(R.layout.fragment_activity_main, container, false) 24 | } 25 | 26 | override fun onDestroyView() { 27 | super.onDestroyView() 28 | recyclerView.adapter = null 29 | } 30 | 31 | override fun onViewCreated(view: View, savedInstanceState: Bundle?) { 32 | super.onViewCreated(view, savedInstanceState) 33 | 34 | recyclerView.layoutManager = LinearLayoutManager(activity!!) 35 | recyclerView.adapter = adapter 36 | } 37 | } -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | apply plugin: 'kotlin-android' 4 | 5 | apply plugin: 'kotlin-android-extensions' 6 | 7 | android { 8 | compileSdkVersion 28 9 | defaultConfig { 10 | applicationId "com.yfujiki.recyclerviewmemoryleak" 11 | minSdkVersion 14 12 | targetSdkVersion 28 13 | versionCode 1 14 | versionName "1.0" 15 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 16 | } 17 | buildTypes { 18 | release { 19 | minifyEnabled false 20 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 21 | } 22 | } 23 | } 24 | 25 | dependencies { 26 | implementation fileTree(dir: 'libs', include: ['*.jar']) 27 | implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" 28 | implementation 'androidx.appcompat:appcompat:1.1.0-alpha01' 29 | implementation 'androidx.constraintlayout:constraintlayout:2.0.0-alpha3' 30 | testImplementation 'junit:junit:4.12' 31 | androidTestImplementation 'androidx.test:runner:1.1.1' 32 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1' 33 | 34 | implementation 'io.reactivex.rxjava2:rxkotlin:2.3.0' 35 | 36 | debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.6.2' 37 | releaseImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:1.6.2' 38 | debugImplementation 'com.squareup.leakcanary:leakcanary-support-fragment:1.6.2' 39 | } 40 | -------------------------------------------------------------------------------- /app/src/main/java/com/yfujiki/recyclerviewmemoryleak/MainRecyclerViewAdapter.kt: -------------------------------------------------------------------------------- 1 | package com.yfujiki.recyclerviewmemoryleak 2 | 3 | import android.view.LayoutInflater 4 | import android.view.View 5 | import android.view.ViewGroup 6 | import androidx.recyclerview.widget.RecyclerView 7 | import io.reactivex.disposables.CompositeDisposable 8 | import io.reactivex.rxkotlin.plusAssign 9 | import kotlinx.android.synthetic.main.view_holder_main.view.* 10 | 11 | class MainRecyclerViewAdapter(val activityDisposable: CompositeDisposable) : RecyclerView.Adapter() { 12 | override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainRecyclerViewHolder { 13 | val itemView = LayoutInflater.from(parent.context).inflate(R.layout.view_holder_main, parent, false) 14 | return MainRecyclerViewHolder(itemView, activityDisposable) 15 | } 16 | 17 | override fun getItemCount(): Int { 18 | return 10 19 | } 20 | 21 | override fun onBindViewHolder(holder: MainRecyclerViewHolder, position: Int) { 22 | holder.itemView.textView.text = position.toString() 23 | } 24 | } 25 | 26 | class MainRecyclerViewHolder(itemView: View, val activityDisposable: CompositeDisposable): RecyclerView.ViewHolder(itemView) { 27 | val disposable = CompositeDisposable() 28 | 29 | init { 30 | disposable += AppState.stateSubject.subscribe { 31 | itemView.textView.text = "Status : $it" 32 | someMethod() 33 | } 34 | activityDisposable.add(disposable) 35 | } 36 | 37 | fun someMethod() { 38 | println("Doing nothing...") 39 | } 40 | 41 | protected fun finalize() { 42 | if (!disposable.isDisposed) { 43 | disposable.dispose() 44 | } 45 | 46 | println("MainRecyclerViewHolder reclaimed") 47 | } 48 | } -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 12 | 13 | 19 | 22 | 25 | 26 | 27 | 28 | 34 | 35 | -------------------------------------------------------------------------------- /.idea/codeStyles/Project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | 7 | 8 | 18 | 19 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 34 | 35 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 19 | 31 | 32 | 33 | 34 | 35 | 36 | 38 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 10 | 12 | 14 | 16 | 18 | 20 | 22 | 24 | 26 | 28 | 30 | 32 | 34 | 36 | 38 | 40 | 42 | 44 | 46 | 48 | 50 | 52 | 54 | 56 | 58 | 60 | 62 | 64 | 66 | 68 | 70 | 72 | 74 | 75 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /README-ja.md: -------------------------------------------------------------------------------- 1 | Android を触り始めて1年弱、[LeakCanary](https://github.com/square/leakcanary) を初めて使ってみたところ、普通に使っているつもりだった `RecyclerView` 周りでメモリリークを起こしていると怒られたので、[サンプルプログラム](https://github.com/yfujiki/RecyclerViewMemoryLeak) を作って調べてみました。なお、サンプルは全て Kotlin です。 2 | 3 | ## ケース 1. `RecyclerView.adapter` が `Activity` よりも長生きする場合 4 | 5 | ### メモリリーク 6 | このサンプルは、下図のようなベーシックな構造をとっています。 7 | 8 | ![Structure.png](https://qiita-image-store.s3.amazonaws.com/0/108030/5010b434-46aa-de0f-f437-3865872c9a38.png) 9 | 10 | `Fragment` が `RecyclerView` を表示していて、その `adapter` がカスタムの `ViewHolder` を供給しています。一つだけ、通常(!?) の構造から逸脱しているとすれば、それは `Fragment` が `adapter` への参照を保持していることです。せっかく `Fragment` を使っているので、`adapter` の生存時間を `Fragment` に合わせ、回転等が起きても `adapter` の状態を維持できるようにしています。 11 | 12 | しかし、この参照が、どうもメモリリークを引き起こすようです。 13 | 14 | [LeakCanary](https://github.com/square/leakcanary) によるリークのツリーは以下のようになります。 15 | 16 | ![Adapter.png](https://qiita-image-store.s3.amazonaws.com/0/108030/343ca8a3-ed73-f31e-d21b-a419d9100872.png) 17 | 18 | これによると、GC root から `RecyclerView.mAdapter` への参照が保持される限り、`Activity` がリークする、と読めます。 19 | 20 | つまり、どうも `RecyclerView.Adapter` から `RecyclerView` 経由で `Activity` への参照が内部的に張られているようです。 (下図点線参照) 21 | 22 | ![structure-actual-for-adapter.png](https://qiita-image-store.s3.amazonaws.com/0/108030/db0c18e6-e381-9503-49ff-bfcbe682ff1f.png) 23 | 24 | 25 | ### 解決法 1 26 | 27 | `adapter` の生存期間を `Activity` に合わせる。 28 | 29 | ```kotlin 30 | class MainActivityFragment : Fragment() { 31 | // Discard permanent reference to the adapter 32 | - val adapter = MainRecyclerViewAdapter() 33 | - 34 | override fun onCreate(savedInstanceState: Bundle?) { 35 | super.onCreate(savedInstanceState) 36 | return inflater.inflate(R.layout.fragment_activity_main, container, false) 37 | } 38 | 39 | override fun onViewCreated(view: View, savedInstanceState: Bundle?) { 40 | super.onViewCreated(view, savedInstanceState) 41 | 42 | // Recreate adapter instance every time after rotation 43 | - recyclerView.adapter = adapter 44 | + recyclerView.adapter = MainRecyclerViewAdapter() 45 | recyclerView.layoutManager = LinearLayoutManager(activity!!) 46 | } 47 | } 48 | ``` 49 | 50 | この解決方法は、原因を考えればわかりやすいですが、 `adapter` に状態を保持できなくなる、という欠点があります。回転が起きると `adapter` は毎度初期化されるので、状態はどこか別に保存しておいて、そこから随時読み込むという形にする必要があります。 51 | 52 | ### 解決法 2 53 | 54 | `onDestroyView` で `recyclerView.adapter = null` を呼んでやるだけです。 55 | 56 | ```kotlin 57 | class MainActivityFragment : Fragment() { 58 | // Discard permanent reference to the adapter 59 | val adapter = MainRecyclerViewAdapter() 60 | 61 | override fun onCreate(savedInstanceState: Bundle?) { 62 | super.onCreate(savedInstanceState) 63 | return inflater.inflate(R.layout.fragment_activity_main, container, false) 64 | } 65 | 66 | + override fun onDestroyView() { 67 | + super.onDestroyView() 68 | + recyclerView.adapter = null 69 | + } 70 | + 71 | override fun onViewCreated(view: View, savedInstanceState: Bundle?) { 72 | super.onViewCreated(view, savedInstanceState) 73 | recyclerView.adapter = adapter 74 | } 75 | } 76 | ``` 77 | 78 | 詳細は Android のコードを読まないとわかりませんが、`RecyclerView` => `adapter` の参照を切った時に `adapter` から `RecyclerView` の隠れ参照 (!?) も切ってくれて、循環参照がなくなるのだと思います。 79 | 80 | 81 | ### ケース 1 のまとめ 82 | 83 | 解決法 1 は「`adapter`に状態を持たせられない」という制限ができてしまうので、解決法 2 が汎用的でより良いと思われます。 84 |  85 | 一つ付け加えて起きたいのは、このタイプのメモリリークは `ViewPager` では起きません。おそらく、隠れ参照の張られ方が `RecyclerView` と違うのだと思います。 86 | 87 | ## ケース 2. Rx の `disposable` を `RecyclerView.ViewHolder` で使い、dispose しなかった/できなかった場合。 88 | 89 | ### メモリリーク 90 | 91 | これは、`RecyclerView` に限った話ではなく、`Disposable` を dispose せずに放ってしまったという一般的なバグで起きることですが、「いつ dispose したらいいんだ」という問題は結構あって、 `RecyclerView` 特有の問題かな、と思いました。 92 | 93 | ```kotlin 94 | class MainRecyclerViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) { 95 | val disposable = CompositeDisposable() 96 | 97 | init { 98 | disposable += AppState.stateSubject.subscribe { 99 | itemView.textView.text = "Status : $it" 100 | someMethod() 101 | } 102 | } 103 | 104 | fun someMethod() { 105 | println("Doing nothing...") 106 | } 107 | } 108 | ``` 109 | 110 | カスタムの `ViewHolder` インスタンスが、スタティックな Rx `subject` に subscribe しています。明らかにここでは disposable を dispose してないんで、subscribe ブロックがリークします。ただ、それだけではなく、subscriber ブロックが `ViewHolder` への参照を持っているため `ViewHolder` がリークし、`ViewHolder` も内部的に `Activity` への参照を持っているようで `Activity` もリークします。LeakCanary によるリークツリーは以下のようになります。: 111 | 112 | ![RxSubscriber.png](https://qiita-image-store.s3.amazonaws.com/0/108030/70955e74-df4f-098b-e79b-075376a803fe.png) 113 | 114 | 内部的には `ViewHolder` から `Activity` への参照があるということが伺えます。 115 | 116 | ![Structure-actual-for-view-holder.png](https://qiita-image-store.s3.amazonaws.com/0/108030/8a0fbebf-a678-7ffe-e089-f26b66601e97.png) 117 | 118 | 119 | ### 解決法 1 120 | 121 | `disposable` を `ViewHolder.finalize()` で `dispose` します。この時気をつけないといけないのは、subscriber ブロックから `ViewHolder` への参照は WeakReference で行なわないといけないということです。そうしないと、subscriber ブロックからの参照が生きているので `ViewHolder.finalize()` が永久に呼ばれず、`dispose` も呼ばれないことになってしまいます。 122 | 123 | ```kotlin 124 | val disposable = CompositeDisposable() 125 | 126 | init { 127 | + val weakItemView = WeakReference(itemView) 128 | + val weakSelf = WeakReference(this) 129 | + 130 | disposable += AppState.stateSubject.subscribe { 131 | - itemView.textView.text = "Status : $it" 132 | - someMethod() 133 | + weakItemView.get()?.textView?.text = "Status : $it" 134 | + weakSelf.get()?.someMethod() 135 | } 136 | } 137 | 138 | fun someMethod() { 139 | println("Doing nothing...") 140 | } 141 | + 142 | + protected fun finalize() { 143 | + if (!disposable.isDisposed()) { 144 | + disposable.dispose() 145 | + } 146 | + println("MainRecyclerViewHolder reclaimed") 147 | + } 148 | ``` 149 | 150 | この方法には `finalize()` がいつ呼ばれるか分からない、という問題があります。回転が起きた後 `ViewHolder` のインスタンスが画面からはデタッチされた後でも、GC が呼ばれるまで `finalize()` は呼ばれません。なので、GC が起きるまでの間、画面に表示されない `ViewHolder` インスタンスがゾンビのように生きていて Rx イベントを受け続けるという状態が起こり得ます。 151 | 152 | ### 解決法 2 153 | `Activity` で `Disposable` インスタンスを生成し、パラメータとして `ViewHolder` まで受け渡し、`ViewHolder` ではそれを使う、という方法です。これで、回転が起きて `Activity` が死んだ時には、GC を待たずに subscriber ブロックも dispose することができます。 154 | 155 | MainActivity: 156 | 157 | ```kotlin 158 | class MainActivity : AppCompatActivity() { 159 | + val disposable = CompositeDisposable() 160 | 161 | override fun onCreate(savedInstanceState: Bundle?) { 162 | super.onCreate(savedInstanceState) 163 | setContentView(R.layout.activity_main) 164 | } 165 | 166 | + override fun onDestroy() { 167 | + super.onDestroy() 168 | + 169 | + if (!disposable.isDisposed) { 170 | + disposable.dispose() 171 | + } 172 | + } 173 | ``` 174 | 175 | MainActivityFragment: 176 | 177 | ```kotlin 178 | class MainActivityFragment : Fragment() { 179 | 180 | - val adapter = MainRecyclerViewAdapter() 181 | + private lateinit var adapter: MainRecyclerViewAdapter 182 | 183 | override fun onCreate(savedInstanceState: Bundle?) { 184 | super.onCreate(savedInstanceState) 185 | 186 | + adapter = MainRecyclerViewAdapter((activity as MainActivity).disposable) 187 | retainInstance = true 188 | } 189 | ... 190 | ``` 191 | 192 | MainRecyclerViewAdapter: 193 | 194 | ```kotlin 195 | -class MainRecyclerViewAdapter: RecyclerView.Adapter() { 196 | +class MainRecyclerViewAdapter(val activityDisposable: CompositeDisposable) : RecyclerView.Adapter() { 197 | override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainRecyclerViewHolder { 198 | val itemView = LayoutInflater.from(parent.context).inflate(R.layout.view_holder_main, parent, false) 199 | - return MainRecyclerViewHolder(itemView) 200 | + return MainRecyclerViewHolder(itemView, activityDisposable) 201 | } 202 | ... 203 | ``` 204 | 205 | MainRecyclerViewHolder: 206 | 207 | ```kotlin 208 | -class MainRecyclerViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) { 209 | +class MainRecyclerViewHolder(itemView: View, val activityDisposable: CompositeDisposable): RecyclerView.ViewHolder(itemView) { 210 | val disposable = CompositeDisposable() 211 | 212 | init { 213 | disposable += AppState.stateSubject.subscribe { 214 | itemView.textView.text = "Status : $it" 215 | someMethod() 216 | } 217 | + activityDisposable.add(disposable) 218 | } 219 | } 220 | ``` 221 | 222 | `ViewHolder` の生存期間が `Activity` と同じであると保証できる場合には解決法 2 は万全です。 223 | 224 | しかし、`ViewHolder` が `Activity` が死んでからも生き続けるケースがある場合には (ソフトキーボード?)この方法はまずいです。`Activity` が死んだ後は、受け取るべきイベントを受けれない `ViewHolder` が出てきてしまいます。 225 | 226 | また、`Activity` がまだ生きている間に `ViewHolder` が死ぬケースがある場合も問題です(複数の `Fragment` が `Activity` によって切り変えられるケース、など)。死んだはずの `ViewHolder` が Rx イベントを受け続ける事態が発生します。しかしこの場合は、`Activity` の代わりに `Fragment` の生存期間を `ViewHolder` と合わせてやればいいので、`Activity` ではなく、`Fragment`から `Disposable` を渡せばいいはずです。 227 | 228 | ### ケース 2 のまとめ 229 | 230 | 該当スクリーンがソフトキーボードを表示することがない場合、解決法 2 は有効です。`Activity` が複数 `Fragment` を切り替えて使用している場合には、`Activity` の代わりに、`Fragment`から `Disposable` を渡せばいいはずです。 231 | 232 | ちょっと調べる必要がありますが、ソフトキーボードを表示する場合でもその時表示されている `ViewHolder` が破棄されるのであれば、やはり問題はないはずです。そこはちょっと宿題。。 233 | 234 | `ViewHolder` が死ぬ時に確実に呼ばれるコールバックがあれば (`onDestroy` 的な) 簡単に解決するのになぁ。。 235 | 236 | ## 総括 237 | 238 | - `RecyclerView.Adapter` が `Activity` より長生きした場合に `Activity` がリークする可能性があることと、その解決法を示しました。 239 | - `RecyclerView.ViewHolder` で Rx を使った時に `Activity` がリークする可能性と、その場合の限定的な解決法を示しました。 240 | 241 | 全く意識してませんでしたが、LeakCanary のリークツリーによると、 `RecyclerView.Adapter`/`RecyclerView.ViewHolder` から `Activity` への隠れ参照があるようです。 242 | 243 | LeakCanary は最高ですね。最初は少々疑って、自分でも `Activity` の `finalize()` メソッドが呼ばれているかどうかをチェックして `Activity` のリークを確認しましたが、LeakCanary のリークレポートと完全に一致していました。今後全てのプロジェクトで使っていきたいツールです。 244 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![platform](https://img.shields.io/badge/platform-Android-blue.svg) 2 | ![language](https://img.shields.io/badge/language-Kotlin1.3-green.svg) 3 | ![twitter](https://img.shields.io/badge/twitter-@yfujiki-blue.svg) 4 | 5 | ## Preface 6 | This repository is mostly meant for novis to mid level Android programmers, who haven't really digged into [LeakCanary](https://github.com/square/leakcanary) yet. I myself used it for the first time recently after delving into Android development for a year. And I am pleasantly surprised how powerful this tool is. This is definitely a must-include tool in every project. At the same time, I was surprised how Android maintains references under the hood for `RecyclerViews`. With naive expectation that `RecyclerView` itself should avoid circular references, you can easily fall into a trap of memory leaks. (And that's exactly the kind of reason that Square guys implemented [LeakCanary](https://github.com/square/leakcanary) and everybody should use it) 7 | 8 | ## How to use LeakCanary 9 | It's pretty simple to use LeakCanary. As instructed in the [README section](https://github.com/square/leakcanary#getting-started), you just need to **1. describe dependency in gradle** and **2. write a few lines in your `Application` subclass**. And then LeakCanary will alert you of the memory leak in your __debug build__. 10 | 11 | However, as straight-forward as it sounds, there was one pitfall I got into. If you are like me and prefers to press _Debug_ button instead of _Run_ button on Android Studio, **LeakCanary doesn't run while you are debugging**. You have to stop the debugging, and start the installed debug build from the launcher. 12 | 13 | I have summarized this flow into a video, if this helps : 14 | 15 | [![How to use LeakCanary](http://img.youtube.com/vi/RiYGSjguI9k/0.jpg)](http://www.youtube.com/watch?v=RiYGSjguI9k "How to use LeakCanary ((after you have finished implementation)") 16 | 17 | ## Two cases you can easily make memory leak around RecyclerView 18 | 19 | I have put two cases of memory leaks I encountered into this sample program. All codes are written in Kotlin. 20 | 21 | ### Case 1: `RecyclerView.adapter` outlives `Activity`. 22 | 23 | #### Memory Leak: 24 | This sample program follows very standard structure as follows. 25 | 26 | ![Structure.png](./Resources/Structure.png) 27 | 28 | `Fragment` shows `RecyclerView` and it's `adapter` provides custom `Viewholder`s. One thing that deviates from standard(!?) structure is that the `Fragment` keeps reference to the `adapter`. This reference is meant to reuse `adapter` even after `Activity` is refreshed due to rotation etc. We are showing `RecyclerView` on top of the `Fragment`, so I think it is a sensible option to match the lifetime of `RecyclerView`'s `adapter` to the one of the `Fragment`. 29 | 30 | This structure looks memory leak safe because there is no circular references. However, the expectation is false and LeakCanary detects that. 31 | 32 | The object reference path provided by [LeakCanary](https://github.com/square/leakcanary) looks like this. 33 | 34 | ![Adapter.png](https://qiita-image-store.s3.amazonaws.com/0/108030/343ca8a3-ed73-f31e-d21b-a419d9100872.png) 35 | 36 | To my surprise, this diagram tells me that `RecyclerView.mAdapter` holds an indirect reference to `MainActivity` through `RecyclerView.mContext`. This is not a reference we made ourselves. This is a "hidden" reference, if we may call it. 37 | 38 | So, the actual structure with this "hidden" reference (indicated by the dashed lines) is like the next diagram. 39 | 40 | ![structure-actual-for-adapter.png](Resources/structure-actual-for-adapter.png) 41 | 42 | You can see there is a beautiful circular reference from `MainFragment` => `MainRecyclerViewAdapter` => `RecyclerView` => `MainActivity` => `MainFragment` and so on... Rotation happens, and `MainActivity` gets recreated, but since `MainFragment` still lives after rotation and keeps indirect reference to the old `MainActivity`, the old `MainActivity` will never reclaimed by GC and leaks. 43 | 44 | As a side note, the `RecyclerView` is always recreated after rotation and reference from `MainFragment` to the old `RecyclerView` through Android-Kotlin extension never stays after rotation (indicated by the red cross in the diagram). That's how Android works. 45 | 46 | #### Solution 1 47 | 48 | A simple solution is to shorten the lifetime of `adapter` to match with the one of the `Activity`. 49 | 50 | ```kotlin 51 | class MainActivityFragment : Fragment() { 52 | // Discard permanent reference to the adapter 53 | - val adapter = MainRecyclerViewAdapter() 54 | - 55 | override fun onCreate(savedInstanceState: Bundle?) { 56 | super.onCreate(savedInstanceState) 57 | return inflater.inflate(R.layout.fragment_activity_main, container, false) 58 | } 59 | 60 | override fun onViewCreated(view: View, savedInstanceState: Bundle?) { 61 | super.onViewCreated(view, savedInstanceState) 62 | 63 | // Recreate adapter instance every time after rotation 64 | - recyclerView.adapter = adapter 65 | + recyclerView.adapter = MainRecyclerViewAdapter() 66 | recyclerView.layoutManager = LinearLayoutManager(activity!!) 67 | } 68 | } 69 | ``` 70 | 71 | Every time when rotation happens, you will ditch `adapter` that holds an indirect reference to the old `Activity`, so that the `Activity` will not have a zombie reference. 72 | 73 | In terms of structure, we don't have the circular reference we had before, because there is no link from `Fragment` to `adapter` now. 74 | 75 | ![structure-after-removing-adapter.png](Resources/structure-after-removing-adapter-reference.png) 76 | 77 | The cons of this approach is that you cannot save the temporary state in the `adapter`, because the `adapter` is initialized at every rotation. We have to save the temporary state somewhere else, and let the `adapter` to fetch the state after every initialization. 78 | 79 | #### Solution 2 80 | 81 | Another simple solution is to call `recyclerView.adapter = null` from `onDestroyView`. 82 | 83 | ```kotlin 84 | class MainActivityFragment : Fragment() { 85 | // Discard permanent reference to the adapter 86 | val adapter = MainRecyclerViewAdapter() 87 | 88 | override fun onCreate(savedInstanceState: Bundle?) { 89 | super.onCreate(savedInstanceState) 90 | return inflater.inflate(R.layout.fragment_activity_main, container, false) 91 | } 92 | 93 | + override fun onDestroyView() { 94 | + super.onDestroyView() 95 | + // Note that this recyclerView is an old one 96 | + // and different instance from the one in onViewCreated. 97 | + recyclerView.adapter = null 98 | + } 99 | + 100 | override fun onViewCreated(view: View, savedInstanceState: Bundle?) { 101 | super.onViewCreated(view, savedInstanceState) 102 | // Note that this recyclerView is a new one 103 | // and different instance from the one in onDestroyView. 104 | recyclerView.adapter = adapter 105 | } 106 | } 107 | ``` 108 | 109 | Actually, I was surprised that this approach works. Even if you null out the reference from `RecyclerView` to `adapter`, as long as the `adapter` has a reference to `RecyclerView`, you still have circular reference. The only way I can comprehend this is that Android nulls out the reference from `adapter` to the `RecyclerView` as well when you null out the reverse relationship, thereby eliminating the circular reference. 110 | 111 | ![structure-after-nullouting-adapter.png](Resources/structure-after-nullouting-adapter.png) 112 | 113 | ### Summary of case 1 114 | 115 | Even though I think solution 1 is by-the-book approach, note that it has a con that you can not let `adapter` to hold temporary status. If you need `adapter` to maintain temporary status, then probably better to pick solution 2. 116 | 117 | Another interesting point I want to note is that this type of memory leak does not occur with `ViewPager`. The way the `ViewPager` set "hidden" references should be a bit different from how `RecyclerView` does it. 118 | 119 | ## Case 2 : When you created Rx `disposable` in `RecyclerView.ViewHolder`, but you didn't/couldn't dispose it 120 | 121 | ### Memory Leak: 122 | 123 | This case actually belongs to Rx domain rather than `RecyclerView` domain, and it is a trivial case in that it happens when you failed to dispose `Disposable` properly. But I found it not very trivial as of __when__ we should dispose `Disposable`, and that perspective is specific to the `RecyclerView`. 124 | 125 | ```kotlin 126 | class MainRecyclerViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) { 127 | val disposable = CompositeDisposable() 128 | 129 | init { 130 | disposable += AppState.stateSubject.subscribe { 131 | itemView.textView.text = "Status : $it" 132 | someMethod() 133 | } 134 | } 135 | 136 | fun someMethod() { 137 | println("Doing nothing...") 138 | } 139 | } 140 | ``` 141 | 142 | A custom `ViewHolder` instance is subscribing to static Rx `subject`. Apparently in this case the subscription block leaks because we are not disposing the `disposable`. However, in addition to that, `ViewHolder` leaks asw well because the subscription block references `ViewHolder`. And to my surprise, the `ViewHolder` has a "hidden" indirect reference to `Activity`, and the `Activity` leaks too. (It surprised me quite a bit in this case especially because we are placing `RecyclerView` on a `Fragment`.) 143 | 144 | The object reference path provided by LeakCanary would look like this. 145 | 146 | ![RxSubscriber.png](Resources/RxSubscriber.png) 147 | 148 | You can see that there is a reference from `MainRecyclerViewHolder` to `MainActivity`. 149 | 150 | ![Structure-actual-for-view-holder.png](Resources/Structure-actual-for-view-holder.png) 151 | 152 | 153 | ### Solution 1 154 | 155 | We can dispose `disposable` in `ViewHolder.finalize()`. One thing you have to note in this case is that you should reference `ViewHolder` instance as a __weak__ reference. Otherwise, the subscription block's reference keeps the `ViewHolder` instance alive, and `ViewHolder.finalize()` is never called. As a result, `disposable.dispose()` is never called as well. 156 | 157 | ```kotlin 158 | val disposable = CompositeDisposable() 159 | 160 | init { 161 | + val weakItemView = WeakReference(itemView) 162 | + val weakSelf = WeakReference(this) 163 | + 164 | disposable += AppState.stateSubject.subscribe { 165 | - itemView.textView.text = "Status : $it" 166 | - someMethod() 167 | + weakItemView.get()?.textView?.text = "Status : $it" 168 | + weakSelf.get()?.someMethod() 169 | } 170 | } 171 | 172 | fun someMethod() { 173 | println("Doing something...") 174 | } 175 | + 176 | + protected fun finalize() { 177 | + if (!disposable.isDisposed()) { 178 | + disposable.dispose() 179 | + } 180 | + println("MainRecyclerViewHolder reclaimed") 181 | + } 182 | ``` 183 | 184 | This solution is probably an anti-pattern. Resorting to implementation in `finalize()` is always frowned upon, because you never know when it will be called. After `ViewHolder` instance was detached from the window after rotation, `finalize()` will not be called until the next GC. I haven't observed this, but it is theoretically possible that the detached `ViewHolder`s keeps receiving Rx events even though they are considered "dead" from application's perspective. 185 | 186 | But you can save this as a last resort. The "dead" instances will be claimed eventually for sure. 187 | 188 | ### Solution 2 189 | 190 | We can create `Disposable` instance in `Activity` instance and trickle it down to `ViewHolder`s for their use. This way, we can match the lifetime of `Disposable` and `Activity. 191 | 192 | MainActivity: 193 | 194 | ```kotlin 195 | class MainActivity : AppCompatActivity() { 196 | + val disposable = CompositeDisposable() 197 | 198 | override fun onCreate(savedInstanceState: Bundle?) { 199 | super.onCreate(savedInstanceState) 200 | setContentView(R.layout.activity_main) 201 | } 202 | 203 | + override fun onDestroy() { 204 | + super.onDestroy() 205 | + 206 | + if (!disposable.isDisposed) { 207 | + disposable.dispose() 208 | + } 209 | + } 210 | ``` 211 | 212 | MainActivityFragment: 213 | 214 | ```kotlin 215 | class MainActivityFragment : Fragment() { 216 | 217 | - val adapter = MainRecyclerViewAdapter() 218 | + private lateinit var adapter: MainRecyclerViewAdapter 219 | 220 | override fun onCreate(savedInstanceState: Bundle?) { 221 | super.onCreate(savedInstanceState) 222 | 223 | + adapter = MainRecyclerViewAdapter((activity as MainActivity).disposable) 224 | retainInstance = true 225 | } 226 | ... 227 | ``` 228 | 229 | MainRecyclerViewAdapter: 230 | 231 | ```kotlin 232 | -class MainRecyclerViewAdapter: RecyclerView.Adapter() { 233 | +class MainRecyclerViewAdapter(val activityDisposable: CompositeDisposable) : RecyclerView.Adapter() { 234 | override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainRecyclerViewHolder { 235 | val itemView = LayoutInflater.from(parent.context).inflate(R.layout.view_holder_main, parent, false) 236 | - return MainRecyclerViewHolder(itemView) 237 | + return MainRecyclerViewHolder(itemView, activityDisposable) 238 | } 239 | ... 240 | ``` 241 | 242 | MainRecyclerViewHolder: 243 | 244 | ```kotlin 245 | -class MainRecyclerViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) { 246 | +class MainRecyclerViewHolder(itemView: View, val activityDisposable: CompositeDisposable): RecyclerView.ViewHolder(itemView) { 247 | val disposable = CompositeDisposable() 248 | 249 | init { 250 | disposable += AppState.stateSubject.subscribe { 251 | itemView.textView.text = "Status : $it" 252 | someMethod() 253 | } 254 | + activityDisposable.add(disposable) 255 | } 256 | } 257 | ``` 258 | 259 | This solution is perfect __in situation where the lifetime of `ViewHolder` and `Activity` should match.__ 260 | 261 | However, if there is a possibility that __`Viewholder` instance outlives `Activity` instance, this solution breaks__. After `Activity` is dead, there will be `ViewHolder`s who cannot receive Rx events. Having said that, I don't come up with any situation that would cause this situation. (i.e., `ViewHolder` to outlive `Activity`) 262 | 263 | On the other hand, if a __`ViewHolder` instance is detached from the window while an `Activity` instance is alive, detached `ViewHolder` could keep receiving Rx events__. This scenario is more realistic. If you have multiple `Fragment`s in the `Activity` and if you are switching the `Fragment`s with `ViewPager`, a `RecyclerView` and its `ViewHolder`s on one `Fragment` could be detached from the window when another `Fragment` is displayed. In this case, __you can trickle down `Disposable`s from the `Fragment` instead of the `Activity`, because you want to match the lifetime of the `ViewHolder` to that of the `Fragment`__. 264 | 265 | ### Summary of case 2 266 | 267 | I think the solution 2 can handle all of the cases. You will need to choose whether to match the `ViewHolder`'s lifetime to `Activity` or `Fragment`, but that's it. 268 | 269 | I don't come up with a situation where `ViewHolder` instance can outlive parent `Activity`/`Fragment` instance, but if you have any idea, I would be pleased to receive a comment. 270 | 271 | My lament is that our life would be so much easier if `ViewHolder` itself had a life cycle callback like `onDestroy`... 272 | 273 | ## Summary 274 | 275 | - Memory leak can happen when `RecyclerView.Adapter` outlives `Activity`. But there is a solution for that! 276 | - Memory leak can happen when you use Rx in `RecyclerView.ViewHolder`. But there is a solution for that! 277 | 278 | I totally didn't have that in my mental model, but according to LeakCanary's reference path, __`RecyclerView.Adapter`/`RecyclerView.Viewholder` has indirect reference to parent `Activity`. (Even when you placed `RecyclerView` on top of a `Fragment`)__. 279 | 280 | ![Actual Structure](Resources/Structure-actual.png) 281 | 282 | Bye bye memory leaks. Long live LeakCanary!! --------------------------------------------------------------------------------