ViewModel Kapsam API'leri Android Jetpack'in bir parçasıdır.

Kapsam, ViewModels'i etkili bir şekilde kullanmanın anahtarıdır. Her ViewModel, ViewModelStoreOwner arayüzünü uygulayan bir nesneye ayarlanır. ViewModel'lerinizin kapsamını daha kolay bir şekilde yönetmenize olanak tanıyan birkaç API vardır. Bu belgede, bilmeniz gereken bazı temel teknikler özetlenmiştir.

ViewModelProvider.get() yöntemi, herhangi bir ViewModelStoreOwner için geçerli olan bir ViewModel örneğini elde etmenizi sağlar. Kotlin kullanıcıları, en yaygın kullanım alanları için farklı uzantı işlevleri vardır. Tüm Kotlin uzantı işlevi uygulamaları, arka planda ViewModelProvider API'yi kullanır.

Kapsamı en yakın ViewModelStoreOwner olarak ayarlanan ViewModels

ViewModel'in kapsamını bir Gezinme grafiğinin bir Etkinliği, Parçası veya hedefi olarak belirleyebilirsiniz. Etkinlik, Parça ve Gezinme kitaplıkları tarafından sağlanan viewModels() uzantısı işlevleri ve Compose'daki viewModel() işlevi, en yakın ViewModelStoreOwner kapsamındaki ViewModel'in bir örneğini almanıza olanak tanır.

Görüntüleme sayısı

import androidx.activity.viewModels

class MyActivity : AppCompatActivity() {
    // ViewModel API available in activity.activity-ktx
    // The ViewModel is scoped to `this` Activity
    val viewModel: MyViewModel by viewModels()
}

import androidx.fragment.app.viewModels

class MyFragment : Fragment() {
    // ViewModel API available in fragment.fragment-ktx
    // The ViewModel is scoped to `this` Fragment
    val viewModel: MyViewModel by viewModels()
}

Görüntüleme sayısı

import androidx.lifecycle.ViewModelProvider;

public class MyActivity extends AppCompatActivity {
    // The ViewModel is scoped to `this` Activity
    MyViewModel viewModel = new ViewModelProvider(this).get(MyViewModel.class);
}

public class MyFragment extends Fragment {
    // The ViewModel is scoped to `this` Fragment
    MyViewModel viewModel = new ViewModelProvider(this).get(MyViewModel.class);
}

Oluştur

import androidx.lifecycle.viewmodel.compose.viewModel

@Composable
fun MyScreen(
    modifier: Modifier = Modifier,
    // ViewModel API available in lifecycle.lifecycle-viewmodel-compose
    // The ViewModel is scoped to the closest ViewModelStoreOwner provided
    // via the LocalViewModelStoreOwner CompositionLocal. In order of proximity,
    // this could be the destination of a Navigation graph, the host Fragment,
    // or the host Activity.
    viewModel: MyViewModel = viewModel()
) { /* ... */ }

Kapsamı herhangi bir ViewModelStoreOwner olarak ayarlanan ViewModels

View sistemindeki ComponentActivity.viewModels() ve Fragment.viewModels() işlevleri ve Compose'daki viewModel() işlevi, ViewModel örneğinin kapsamının hangi ViewModelStoreOwner olacağını belirtmek için kullanabileceğiniz isteğe bağlı bir ownerProducer parametresi alır. Aşağıdaki örnekte, üst parçaya ayarlanan bir ViewModel örneğinin nasıl alınacağı gösterilmektedir:

Görüntüleme sayısı

import androidx.fragment.app.viewModels

class MyFragment : Fragment() {

    // ViewModel API available in fragment.fragment-ktx
    // The ViewModel is scoped to the parent of `this` Fragment
    val viewModel: SharedViewModel by viewModels(
        ownerProducer = { requireParentFragment() }
    )
}

Görüntüleme sayısı

import androidx.lifecycle.ViewModelProvider;

public class MyFragment extends Fragment {

    SharedViewModel viewModel;

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        // The ViewModel is scoped to the parent of `this` Fragment
        viewModel = new ViewModelProvider(requireParentFragment())
            .get(SharedViewModel.class);
    }
}

Oluştur

import androidx.lifecycle.viewmodel.compose.viewModel

@Composable
fun MyScreen(
    context: Context = LocalContext.current,
    // ViewModel API available in lifecycle.lifecycle-viewmodel-compose
    // The ViewModel is scoped to the parent of the host Fragment
    // where this composable function is called
    viewModel: SharedViewModel = viewModel(
        viewModelStoreOwner = (context as Fragment).requireParentFragment()
    )
) { /* ... */ }

Bir Parçadan Etkinlik Kapsamlı ViewModel almak yaygın bir kullanım alanıdır. Bunu yaparken activityViewModels() Görünüm uzantısı işlevini kullanabilirsiniz. Views ve Kotlin kullanmıyorsanız yukarıdaki API'leri kullanarak ve doğru sahibi devredebilirsiniz.

Görüntüleme sayısı

import androidx.fragment.app.activityViewModels

class MyFragment : Fragment() {

    // ViewModel API available in fragment.fragment-ktx
    // The ViewModel is scoped to the host Activity
    val viewModel: SharedViewModel by activityViewModels()
}

Görüntüleme sayısı

import androidx.lifecycle.ViewModelProvider;

public class MyFragment extends Fragment {

    SharedViewModel viewModel;

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        // The ViewModel is scoped to the host Activity
        viewModel = new ViewModelProvider(requireActivity())
            .get(SharedViewModel.class);
    }
}

Oluştur

import androidx.lifecycle.viewmodel.compose.viewModel

@Composable
fun MyScreen(
    context: Context = LocalContext.current,
    // ViewModel API available in lifecycle.lifecycle-viewmodel-compose
    // The ViewModel is scoped to the Activity of the host Fragment
    // where this composable function is called
    viewModel: SharedViewModel = viewModel(
        viewModelStoreOwner = (context as Fragment).requireActivity()
    )
) { /* ... */ }

Gezinme grafiğinin kapsamında yer alan ViewModels

Gezinme grafikleri aynı zamanda ViewModel mağazasının sahipleridir. Gezinme Parçası veya Gezinme Oluşturma özelliğini kullanıyorsanız navGraphViewModels(graphId) Görünüm uzantısı işleviyle Gezinme grafiği kapsamındaki ViewModel'in bir örneğini alabilirsiniz.

Görüntüleme sayısı

import androidx.navigation.navGraphViewModels

class MyFragment : Fragment() {

    // ViewModel API available in navigation.navigation-fragment
    // The ViewModel is scoped to the `nav_graph` Navigation graph
    val viewModel: SharedViewModel by navGraphViewModels(R.id.nav_graph)

    // Equivalent navGraphViewModels code using the viewModels API
    val viewModel: SharedViewModel by viewModels(
        { findNavController().getBackStackEntry(R.id.nav_graph) }
    )
}

Görüntüleme sayısı

import androidx.lifecycle.ViewModelProvider;

public class MyFragment extends Fragment {

    SharedViewModel viewModel;

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        NavController navController = NavHostFragment.findNavController(this);
        NavBackStackEntry backStackEntry = navController.getBackStackEntry(R.id.my_graph);

        // The ViewModel is scoped to the `nav_graph` Navigation graph
        viewModel = new ViewModelProvider(backStackEntry).get(SharedViewModel.class);
    }
}

Oluştur

import androidx.lifecycle.viewmodel.compose.viewModel

@Composable
fun MyAppNavHost() {
    // ...
    composable("myScreen") { backStackEntry ->
        // Retrieve the NavBackStackEntry of "parentNavigationRoute"
        val parentEntry = remember(backStackEntry) {
            navController.getBackStackEntry("parentNavigationRoute")
        }
        // Get the ViewModel scoped to the `parentNavigationRoute` Nav graph
        val parentViewModel: SharedViewModel = viewModel(parentEntry)
        // ...
    }
}

Jetpack Navigation'a ek olarak Hilt kullanıyorsanız hiltNavGraphViewModels(graphId) API'yi aşağıdaki gibi kullanabilirsiniz.

Görüntüleme sayısı

import androidx.hilt.navigation.fragment.hiltNavGraphViewModels

class MyFragment : Fragment() {

    // ViewModel API available in hilt.hilt-navigation-fragment
    // The ViewModel is scoped to the `nav_graph` Navigation graph
    // and is provided using the Hilt-generated ViewModel factory
    val viewModel: SharedViewModel by hiltNavGraphViewModels(R.id.nav_graph)
}

Görüntüleme sayısı

import androidx.hilt.navigation.HiltViewModelFactory;
import androidx.lifecycle.ViewModelProvider;

public class MyFragment extends Fragment {

    SharedViewModel viewModel;

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        NavController navController = NavHostFragment.findNavController(this);
        NavBackStackEntry backStackEntry = navController.getBackStackEntry(R.id.my_graph);

        // The ViewModel is scoped to the `nav_graph` Navigation graph
        // and is provided using the Hilt-generated ViewModel factory
        viewModel = new ViewModelProvider(
            backStackEntry,
            HiltViewModelFactory.create(getContext(), backStackEntry)
        ).get(SharedViewModel.class);
    }
}

Oluştur

import androidx.hilt.navigation.compose.hiltViewModel

@Composable
fun MyAppNavHost() {
    // ...
    composable("myScreen") { backStackEntry ->
        val parentEntry = remember(backStackEntry) {
            navController.getBackStackEntry("parentNavigationRoute")
        }

        // ViewModel API available in hilt.hilt-navigation-compose
        // The ViewModel is scoped to the `parentNavigationRoute` Navigation graph
        // and is provided using the Hilt-generated ViewModel factory
        val parentViewModel: SharedViewModel = hiltViewModel(parentEntry)
        // ...
    }
}