Search code examples
androidandroid-fragmentsandroid-jetpack-composedagger-hilt

Why do I use pure components but still need fragment dependencies?


I have a problem when using compose, then i found the answer

If you use Compose with Fragments, then you may not have the Fragments dependency where viewModels() is defined.

Adding:

implementation "androidx.fragment:fragment-ktx:1.5.2"

use Compose with Fragments, but I use Pure Compose, Also had this problem. What am I missing? Or is there some connection between fragment and compose?


@AndroidEntryPoint
class MainActivity : ComponentActivity() {

    private val userViewModel: UserViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            Content(userViewModel)
        }
    }
}

@Composable
fun Content(userViewModel: UserViewModel) {

    val lazyArticleItem = userViewModel.list().collectAsLazyPagingItems()

    thread {
        repeat(200) {
            userViewModel.insert(User())
        }
    }

    LazyColumn(verticalArrangement = Arrangement.spacedBy(16.dp)) {
        items(lazyArticleItem) { user ->
            Text("user ${user?.id}")
        }
    }

}

The above is my ui interface code, based on this, I don't think I'm using fragment.

I want to declare my logic. I use Pure Compose instead of Fragment, but actually want to run the code must depend on androidx.fragment:fragment-ktx:1.5.2


Solution

  • It happens because you are using

    val userViewModel: UserViewModel by viewModels()
    

    You can access a ViewModel from any composable by calling the viewModel() function.
    Use:

    val userViewMode : UserViewModel = viewModel()
    

    To use the viewModel() functions, add the androidx.lifecycle:lifecycle-viewmodel-compose:x.x.x