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

Detect premature initialization of androidx ViewModel #19

Open
jacob-peterson opened this issue Jan 31, 2023 · 2 comments
Open

Detect premature initialization of androidx ViewModel #19

jacob-peterson opened this issue Jan 31, 2023 · 2 comments

Comments

@jacob-peterson
Copy link
Collaborator

When lazy loading a ViewModel any references to the ViewModel property before Fragment.onAttach will cause an IllegalStateException.

We should detect premature access of a ViewModel during Fragment initialization in Kotlin and Java.

@jacob-peterson
Copy link
Collaborator Author

class ExampleFragment: Fragment() {
    @Inject
    lateinit var exampleViewModelFactory: ExampleViewModel.Factory
    
    private val viewModel by viewModels<ExampleViewModel> {
        ExampleViewModel.provideFactory(exampleViewModelFactory)
    }
    
    // Violation
    private val exampleComponent = ExampleComponent(viewModel.state)
    
    init {
        // Violation
        viewModel.state.collectLatest {

        }
    }
}

@jzbrooks
Copy link
Contributor

It might be prudent to double check that androidx.lifecycle hasn't shipped this in more recent version of the lifecycle library. They might be interested in an external contribution if we get something working, also.

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

No branches or pull requests

2 participants