Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

method Fragment.viewModel is not completely lazy. #1395

Closed
Copatych opened this issue Jul 28, 2022 · 2 comments
Closed

method Fragment.viewModel is not completely lazy. #1395

Copatych opened this issue Jul 28, 2022 · 2 comments

Comments

@Copatych
Copy link

Bug description

Previously (koin 3.1.2), when val viewModel: AbcdeViewModel by viewModel() was written, all the code was executed lazy.

In the current version (3.2.0), if we look at the source code, we will see that part of the code is executed immediately:

@OptIn(KoinInternalApi::class)
inline fun <reified T : ViewModel> Fragment.viewModel(
    qualifier: Qualifier? = null,
    noinline owner: ViewModelStoreOwnerProducer = { this },
    noinline parameters: ParametersDefinition? = null
): Lazy<T> {
    val scope = getKoinScope()
    return viewModels(ownerProducer = owner) {
        getViewModelFactory<T>(owner(), qualifier, parameters, scope = scope)
    }
}

val scope = getKoinScope() will be called immediately.

There is a project in which each fragment implements the KoinComponent interface as follows

override fun getKoin(): Koin {
    return if (parentFragment is KoinComponent) (parentFragment as KoinComponent).getKoin() else GlobalContext.get()
}

In the fragment constructor, when val ViewModel: AbcdeViewModel by ViewModel() is called, the fragment does not have a parent yet. And by viewModel is always called using GlobalContext

Expected behavior
All code in Fragment.viewModel method is executed lazy.

Used koin version:
koin 3.2.0

Workaround

Something like this

import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import org.koin.androidx.viewmodel.ext.android.getViewModel
import org.koin.core.parameter.ParametersDefinition

inline fun <reified T : ViewModel> Fragment.viewModel(
        noinline parameters: ParametersDefinition? = null
): Lazy<T> {
    return lazy {
        getViewModel(parameters = parameters)
    }
}
@Pfoerd
Copy link
Contributor

Pfoerd commented Aug 4, 2022

Likely a duplicate of #1356

@arnaudgiuliani
Copy link
Member

yes duplicated

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants