Created
December 7, 2023 18:14
-
-
Save jeancsanchez/0d2fe3c677330e335f5740bcd5b3ca29 to your computer and use it in GitHub Desktop.
Extension for sharing ViewModels between Activities with Kotlin Koin. (Extensão para compartilhar ViewModels entre activities com Kotlin Koin).
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
inline fun <retified VM: ViewModel> AppCompatActivity.viewModelShared(): Lazy<VM> { | |
return lazy(LazyThreadSafetyMode.NONE) { | |
val scopeKey = this::class.getActScopeId() | |
var scope: Scope = getKoin().getOrCreateScope( | |
scopeId = scopeKey, | |
qualifier = StringQualifier(scopeKey) | |
) | |
lifecycle.doWhen( | |
onCreate = { | |
scope = getKoin().getOrCreateScope( | |
scopeId = scopeKey, | |
qualifier = StringQualifier(scopeKey) | |
) | |
}, | |
onDestroy = { | |
if(scope.isNotClosed()) { | |
scope.close() | |
} | |
} | |
scope.get() | |
} | |
inline fun <retified VM: ViewModel, retified ACTIVITY: AppCompatActivity> AppCompatActivity.sharedViewModel(): Lazy<VM> { | |
return lazy(LazyThreadSafetyMode.NONE) { | |
val scopeKey = ACTIVITY::class.getActScopeId() | |
val koin = getKoin() | |
var scope = koin.getScopeOrNull(scopeKey) | |
if(scope == null) { | |
scope = koin.createScope( | |
scopeId = scopeKey, | |
qualifier = StringQualifier(scopeKey) | |
) | |
lifecycle.doWhen( | |
onDestroy = { | |
if (scope.isNotClosed()) { | |
scope.close() | |
} | |
} | |
) | |
} | |
} | |
} | |
inline fun <retified ACTIVITY: AppCompatActvity> Module.viewModelSharedScope( | |
noninline scopeSet: ScopeDSL.() -> Unit | |
) { | |
scope( | |
qualifier = named(ACTIVITY::class.getActScopeId()), | |
scopeSet = scopeSet | |
) | |
} | |
fun Lifecycle.doWhen( | |
onCreate: (() -> Unit)? = null, | |
onDestroy: (() -> Unit) | |
) { | |
addObserver ( object: LifecycleEventObserver { | |
override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) { | |
when(event) { | |
Lifecycle.Event.ON_CREATE -> onCreate?.invoke() | |
Lifecycle.Event.ON_DESTROY -> onDestroy() | |
else -> Unit | |
} | |
} | |
}) | |
} | |
private fun KClass<*>.getActScopeId(): String = "${this.java.simpleName}-SharedActivityScope" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to use: