# ViewModelKt

Added in 2.8.0

*** ** * ** ***


```
public final class ViewModelKt
```

<br />

*** ** * ** ***

## Summary

| ### Public methods |
|---|---|
| `static final @https://developer.android.com/reference/androidx/annotation/NonNull https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope/index.html` | `https://developer.android.com/reference/androidx/lifecycle/ViewModelKt#(androidx.lifecycle.ViewModel).getViewModelScope()(@https://developer.android.com/reference/androidx/annotation/NonNull https://developer.android.com/reference/androidx/lifecycle/ViewModel receiver)` The `https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope/index.html` associated with this `https://developer.android.com/reference/androidx/lifecycle/ViewModel`. |

## Public methods

### getViewModelScope

Artifact: [androidx.lifecycle:lifecycle-viewmodel](https://developer.android.com/jetpack/androidx/releases/lifecycle) [View Source](https://cs.android.com/search?q=file:androidx/lifecycle/ViewModel.kt+symbol:viewModelScope) Added in [2.8.0](https://developer.android.com/jetpack/androidx/releases/lifecycle#2.8.0)

```
public static final @NonNull CoroutineScope getViewModelScope(@NonNull ViewModel receiver)
```

The `https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope/index.html` associated with this `https://developer.android.com/reference/androidx/lifecycle/ViewModel`.

The `https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope/coroutine-context.html` is configured with:

- `https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/index.html`: ensures children jobs can fail independently of each other.

- `https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-main-coroutine-dispatcher/immediate.html`: executes jobs immediately on the main (UI) thread. If the `https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-main.html` is not available on the current platform (e.g., Linux), we fall back to an `https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.coroutines/-empty-coroutine-context/index.html`.

This scope is automatically canceled when the `https://developer.android.com/reference/androidx/lifecycle/ViewModel` is cleared, and can be replaced by using the `https://developer.android.com/reference/androidx/lifecycle/ViewModel` constructor overload that takes in a `viewModelScope: CoroutineScope`.

For background execution, use `https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/index.html` to switch to appropriate dispatchers (e.g., `kotlinx.coroutines.IO`).

| See also |
|---|---|
| `https://developer.android.com/reference/androidx/lifecycle/ViewModel#onCleared()` |   |