Created
February 12, 2022 22:11
-
-
Save Abdallah-Abdelazim/45cbf61e1556b5b7ccfc1bd805573d09 to your computer and use it in GitHub Desktop.
AutoClearedValue: A lazy property that gets cleaned up when the fragment's view is destroyed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Copyright (C) 2018 The Android Open Source Project | |
* | |
* Licensed under the Apache License, Version 2.0 (the "License"); | |
* you may not use this file except in compliance with the License. | |
* You may obtain a copy of the License at | |
* | |
* http://www.apache.org/licenses/LICENSE-2.0 | |
* | |
* Unless required by applicable law or agreed to in writing, software | |
* distributed under the License is distributed on an "AS IS" BASIS, | |
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
* See the License for the specific language governing permissions and | |
* limitations under the License. | |
*/ | |
package com.android.example.github.util | |
import androidx.fragment.app.Fragment | |
import androidx.lifecycle.DefaultLifecycleObserver | |
import androidx.lifecycle.LifecycleOwner | |
import androidx.lifecycle.observe | |
import kotlin.properties.ReadWriteProperty | |
import kotlin.reflect.KProperty | |
/** | |
* A lazy property that gets cleaned up when the fragment's view is destroyed. | |
* | |
* Accessing this variable while the fragment's view is destroyed will throw NPE. | |
*/ | |
class AutoClearedValue<T : Any>(val fragment: Fragment) : ReadWriteProperty<Fragment, T> { | |
private var _value: T? = null | |
init { | |
fragment.lifecycle.addObserver(object: DefaultLifecycleObserver { | |
override fun onCreate(owner: LifecycleOwner) { | |
fragment.viewLifecycleOwnerLiveData.observe(fragment) { viewLifecycleOwner -> | |
viewLifecycleOwner?.lifecycle?.addObserver(object: DefaultLifecycleObserver { | |
override fun onDestroy(owner: LifecycleOwner) { | |
_value = null | |
} | |
}) | |
} | |
} | |
}) | |
} | |
override fun getValue(thisRef: Fragment, property: KProperty<*>): T { | |
return _value ?: throw IllegalStateException( | |
"should never call auto-cleared-value get when it might not be available" | |
) | |
} | |
override fun setValue(thisRef: Fragment, property: KProperty<*>, value: T) { | |
_value = value | |
} | |
} | |
/** | |
* Creates an [AutoClearedValue] associated with this fragment. | |
*/ | |
fun <T : Any> Fragment.autoCleared() = AutoClearedValue<T>(this) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In a fragment you can do the following:
This is taken from GithubBrowserSample by Google