Created
October 25, 2020 20:20
-
-
Save johnkil/cd34c025c45a73cb52db76765ce5b17f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import androidx.fragment.app.Fragment | |
import androidx.fragment.app.viewModels | |
import androidx.lifecycle.ViewModel | |
inline fun <reified T> Fragment.nonConfigurationInstance( | |
noinline instanceProducer: () -> T | |
) = NonConfigurationInstanceLazy( | |
instanceProducer = instanceProducer, | |
instanceHolder = viewModels() | |
) | |
class NonConfigurationInstanceHolder<T> : ViewModel() { | |
var nonConfigurationInstance: T? = null | |
} | |
class NonConfigurationInstanceLazy<T>( | |
private val instanceProducer: () -> T, | |
private val instanceHolder: Lazy<NonConfigurationInstanceHolder<T>> | |
) : Lazy<T> { | |
override val value: T | |
get() = with(instanceHolder.value) { | |
nonConfigurationInstance ?: instanceProducer().also { nonConfigurationInstance = it } | |
} | |
override fun isInitialized() = instanceHolder.isInitialized() | |
} | |
class PaymentFragment : Fragment() { | |
private val component by nonConfigurationInstance { | |
DaggerPaymentComponent.factory().create(dependencies) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment