Жизненный цикл
В этой таблице перечислены все артефакты в группе androidx.lifecycle .
| Артефакт | Стабильный релиз | Кандидат на релиз | Бета-версия | Альфа-релиз |
|---|---|---|---|---|
| жизненный цикл-* | 2.9.4 | - | 2.10.0-бета01 | - |
| жизненный цикл-представление-модель-навигация3 | - | - | 2.10.0-бета01 | - |
Объявление зависимостей
Чтобы добавить зависимость от Lifecycle, необходимо добавить репозиторий Google Maven в свой проект. Подробнее см. в репозитории Google Maven .
Добавьте зависимости для необходимых артефактов в файл build.gradle вашего приложения или модуля:
Котлин
Круто
dependencies { def lifecycle_version = "2.9.4" def arch_version = "2.2.0" // ViewModel implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version" // ViewModel utilities for Compose implementation "androidx.lifecycle:lifecycle-viewmodel-compose:$lifecycle_version" // LiveData implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version" // Lifecycles only (without ViewModel or LiveData) implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version" // Lifecycle utilities for Compose implementation "androidx.lifecycle:lifecycle-runtime-compose:$lifecycle_version" // Saved state module for ViewModel implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version" // ViewModel integration with Navigation3 implementation "androidx.lifecycle:lifecycle-viewmodel-navigation3:2.10.0-beta01" // Annotation processor kapt "androidx.lifecycle:lifecycle-compiler:$lifecycle_version" // alternately - if using Java8, use the following instead of lifecycle-compiler implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version" // optional - helpers for implementing LifecycleOwner in a Service implementation "androidx.lifecycle:lifecycle-service:$lifecycle_version" // optional - ProcessLifecycleOwner provides a lifecycle for the whole application process implementation "androidx.lifecycle:lifecycle-process:$lifecycle_version" // optional - ReactiveStreams support for LiveData implementation "androidx.lifecycle:lifecycle-reactivestreams-ktx:$lifecycle_version" // optional - Test helpers for LiveData testImplementation "androidx.arch.core:core-testing:$arch_version" // optional - Test helpers for Lifecycle runtime testImplementation "androidx.lifecycle:lifecycle-runtime-testing:$lifecycle_version" }
Котлин
dependencies { val lifecycle_version = "2.9.4" val arch_version = "2.2.0" // ViewModel implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version") // ViewModel utilities for Compose implementation("androidx.lifecycle:lifecycle-viewmodel-compose:$lifecycle_version") // LiveData implementation("androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version") // Lifecycles only (without ViewModel or LiveData) implementation("androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version") // Lifecycle utilities for Compose implementation("androidx.lifecycle:lifecycle-runtime-compose:$lifecycle_version") // Saved state module for ViewModel implementation("androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version") // ViewModel integration with Navigation3 implementation("androidx.lifecycle:lifecycle-viewmodel-navigation3:2.10.0-beta01") // Annotation processor kapt("androidx.lifecycle:lifecycle-compiler:$lifecycle_version") // alternately - if using Java8, use the following instead of lifecycle-compiler implementation("androidx.lifecycle:lifecycle-common-java8:$lifecycle_version") // optional - helpers for implementing LifecycleOwner in a Service implementation("androidx.lifecycle:lifecycle-service:$lifecycle_version") // optional - ProcessLifecycleOwner provides a lifecycle for the whole application process implementation("androidx.lifecycle:lifecycle-process:$lifecycle_version") // optional - ReactiveStreams support for LiveData implementation("androidx.lifecycle:lifecycle-reactivestreams-ktx:$lifecycle_version") // optional - Test helpers for LiveData testImplementation("androidx.arch.core:core-testing:$arch_version") // optional - Test helpers for Lifecycle runtime testImplementation ("androidx.lifecycle:lifecycle-runtime-testing:$lifecycle_version") }
Ява
Круто
dependencies { def lifecycle_version = "2.9.4" def arch_version = "2.2.0" // ViewModel implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version" // LiveData implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version" // Lifecycles only (without ViewModel or LiveData) implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle_version" // Saved state module for ViewModel implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version" // Annotation processor annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version" // alternately - if using Java8, use the following instead of lifecycle-compiler implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version" // optional - helpers for implementing LifecycleOwner in a Service implementation "androidx.lifecycle:lifecycle-service:$lifecycle_version" // optional - ProcessLifecycleOwner provides a lifecycle for the whole application process implementation "androidx.lifecycle:lifecycle-process:$lifecycle_version" // optional - ReactiveStreams support for LiveData implementation "androidx.lifecycle:lifecycle-reactivestreams:$lifecycle_version" // optional - Test helpers for LiveData testImplementation "androidx.arch.core:core-testing:$arch_version" // optional - Test helpers for Lifecycle runtime testImplementation "androidx.lifecycle:lifecycle-runtime-testing:$lifecycle_version" }
Котлин
dependencies { val lifecycle_version = "2.9.4" val arch_version = "2.2.0" // ViewModel implementation("androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version") // LiveData implementation("androidx.lifecycle:lifecycle-livedata:$lifecycle_version") // Lifecycles only (without ViewModel or LiveData) implementation("androidx.lifecycle:lifecycle-runtime:$lifecycle_version") // Saved state module for ViewModel implementation("androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version") // Annotation processor annotationProcessor("androidx.lifecycle:lifecycle-compiler:$lifecycle_version") // alternately - if using Java8, use the following instead of lifecycle-compiler implementation("androidx.lifecycle:lifecycle-common-java8:$lifecycle_version") // optional - helpers for implementing LifecycleOwner in a Service implementation("androidx.lifecycle:lifecycle-service:$lifecycle_version") // optional - ProcessLifecycleOwner provides a lifecycle for the whole application process implementation("androidx.lifecycle:lifecycle-process:$lifecycle_version") // optional - ReactiveStreams support for LiveData implementation("androidx.lifecycle:lifecycle-reactivestreams:$lifecycle_version") // optional - Test helpers for LiveData testImplementation("androidx.arch.core:core-testing:$arch_version") // optional - Test helpers for Lifecycle runtime testImplementation("androidx.lifecycle:lifecycle-runtime-testing:$lifecycle_version") }
Дополнительную информацию о зависимостях см. в разделе Добавление зависимостей сборки .
Обратная связь
Ваши отзывы помогают улучшить Jetpack. Сообщите нам, если вы обнаружите новые проблемы или у вас есть идеи по улучшению этой библиотеки. Пожалуйста, ознакомьтесь с уже существующими проблемами в этой библиотеке, прежде чем создавать новую. Вы можете проголосовать за существующую проблему, нажав на кнопку со звёздочкой.
Более подробную информацию см. в документации по системе отслеживания проблем .
Версия 2.10
Версия 2.10.0-beta01
22 октября 2025 г.
Выпущен androidx.lifecycle:lifecycle-*:2.10.0-beta01 . Версия 2.10.0-beta01 содержит следующие коммиты .
Изменения API
-
ViewModelStoreNavEntryDecoratorDefaultбыл переименован вViewModelStoreNavEntryDecoratorDefaultsс добавлением «s». ( I6d27b , b/444447434 )
Исправления ошибок
-
rememberLifecycleOwnerбольше не дает сбой, если владелец получает событиеLifecycle.Event.ON_DESTROYдо перехода вLifeycle.State.CREATED. ( I6f98e , b/444594991 )
Версия 2.10.0-альфа05
8 октября 2025 г.
Выпущен androidx.lifecycle:lifecycle-*:2.10.0-alpha05 . Версия 2.10.0-alpha05 содержит следующие коммиты .
Изменения API
-
removeViewModelStoreOnPopCallback()теперь является частью объектаViewModelStoreNavEntryDecoratorDefault, в котором другие платформы и реализации могут вызывать метод по умолчанию. ( Ia1f23 , b/444447434 ) -
ViewModelStoreNavEntryDecoratorбыл преобразован из функции в класс для лучшего отражения его функциональности как фабрики дляNavEntryDecorator, а параметр декоратораshouldRemoveViewModelStoreбыл переименован вremoveViewModelStoreOnPop, чтобы было понятно, что этот обратный вызов вызывается только при извлечении записи изbackStack. ( Iefdc5 , b/444447434 )
Версия 2.10.0-альфа04
24 сентября 2025 г.
Выпущен androidx.lifecycle:lifecycle-*:2.10.0-alpha04 . Версия 2.10.0-alpha04 содержит следующие коммиты .
Изменения API
- Реорганизовать компонуемый объект
LifecycleOwner, включив в негоrememberLifecycleOwner. Теперь функция возвращает объектLifecycleOwnerнапрямую. Чтобы предоставить этого владельца подкомпозиции, используйтеCompositionLocalProvider. ( Ic57f0 , b/444446629 ) - Добавьте заглушки KMP в lifecycle-viewmodel-navigation3, чтобы JetBrains мог предоставлять вилки, которые заполняют эти цели и, таким образом, поддерживают CMP. ( I44a4c )
Версия 2.10.0-альфа03
27 августа 2025 г.
Выпущен androidx.lifecycle:lifecycle-*:2.10.0-alpha03 . Версия 2.10.0-alpha03 содержит следующие коммиты .
Изменения API
- Обновите Compose до версии 1.9.0. ( I2b9de )
Версия 2.10.0-альфа02
13 августа 2025 г.
Выпущен androidx.lifecycle:lifecycle-*:2.10.0-alpha02 . Версия 2.10.0-alpha02 содержит следующие коммиты .
Новые функции
Композируемый объект
LifecycleOwnerтеперь может создавать автономный корневой жизненный цикл . Если (явно) задатьparent = null, новый жизненный цикл будет работать независимо от любого хоста (например,Activity,FragmentилиNavBackStackEntry). Он запускается сразу после попадания композируемого объекта в композицию и автоматически уничтожается при выходе из неё. ( I8dfbe , b/433659048 )@Composable fun IndependentComponent() { // Create a standalone lifecycle, not tied to the parent Activity/Fragment. LifecycleOwner(parent = null) { val rootLifecycle = LocalLifecycleOwner.current.lifecycle } }
Изменения API
- В компонуемом объекте
LifecycleOwnerпараметрparentLifecycleOwnerбыл переименован вparent. ( I080bc )
Исправления ошибок
- Компонуемый объект
LifecycleOwnerтеперь корректно переводит свой жизненный цикл вDESTROYEDпри уничтожении. Это предотвращает потенциальные утечки внешнего кода, содержащего ссылку на жизненный цикл. ( I9e5b7 , b/433659048 ) - Перемещение minSdk по умолчанию из API 21 в API 23 ( Ibdfca , b/380448311 , b/435705964 , b/435705223 )
Внешний вклад
- Удалить ненужные внутренние поля из
LifecycleOwner. Спасибо Джейку Уортону за вклад. ( Ideddb )
Версия 2.10.0-альфа01
30 июля 2025 г.
Выпущен androidx.lifecycle:lifecycle-*:2.10.0-alpha01 . Версия 2.10.0-alpha01 содержит следующие коммиты .
Новые функции
Добавьте компонуемый объект
LifecycleOwner, чтобы можно было создавать жизненные циклы с ограниченной областью действия непосредственно в пользовательском интерфейсе. Это полезно для компонентов, которым необходимо независимо управлять своими жизненными циклами. Пример интеграции этого нового компонуемого объекта в Navigation3 см. в aosp/3708610 . ( 76cbf7 )@Composable fun MyComposable() { LifecycleOwner( maxLifecycle = RESUMED, parentLifecycleOwner = LocalLifecycleOwner.current, ) { val childLifecycleOwner = LocalLifecycleOwner.current } }
Изменения API
- Добавить функцию фабрики построителей для
CreationExtras, обеспечивая более удобный и идиоматический API Kotlin. ( Iab2bd ) - Добавить встроенную поддержку типов, допускающих значение NULL, в
SavedStateHandle.saved, упрощая сохранение и восстановление свойств, допускающих значение NULL. ( I54d69 , b/421325690 ) - Пометить конструкторы
SavedStateHandleкак@VisibleForTesting. ( Iff0e0 , b/408002794 )
Версия 2.9
Версия 2.9.4
17 сентября 2025 г.
Выпущен androidx.lifecycle:lifecycle-*:2.9.4 . Версия 2.9.4 содержит следующие коммиты .
Исправления ошибок
- Исправлена ошибка, связанная с неприменением плагина Compose Compiler, из-за которой артефакты Lifecycle KMP были повреждены. ( Ie95bc , b/443096483 , b/443965665 )
Версия 2.9.3
27 августа 2025 г.
Выпущен androidx.lifecycle:lifecycle-*:2.9.3 . Версия 2.9.3 содержит следующие коммиты .
Новые функции
- Добавлены новые цели Kotlin Multiplatform (KMP) в артефакты Lifecycle
*-compose. Lifecycle теперь поддерживает следующие платформы: JVM (Android и десктоп), Native (Linux, iOS, watchOS, macOS, MinGW) и Web (JavaScript, WasmJS). ( I0a0e4 )
Исправления ошибок
- Обновление
androidx.annotationдо версии 1.9.1 ( Ic9e4f , b/397701294 )
Версия 2.9.2
16 июля 2025 г.
Выпущен androidx.lifecycle:lifecycle-*:2.9.2 . Версия 2.9.2 содержит следующие коммиты .
Исправления ошибок
- Добавлены новые цели Kotlin Multiplatform (KMP) в артефакты Lifecycle. Lifecycle теперь поддерживает следующие платформы: JVM (Android и десктоп), Native (Linux, iOS, watchOS, macOS, MinGW) и Web (JavaScript, WasmJS). Обратите внимание, что в артефакты
*-composeновые цели KMP не добавлены, так как это зависит от стабильной версии Compose 1.9 ( I01cb8 ).
Обновления зависимостей
- Жизненный цикл теперь зависит от аннотации
1.9.1для обеспечения поддержки новых целей KMP ( Ic9e4f , b/397701294 ).
Версия 2.9.1
4 июня 2025 г.
Выпущен androidx.lifecycle:lifecycle-*:2.9.1 . Версия 2.9.1 содержит следующие коммиты .
Исправления ошибок
- Исправлена ошибка, из-за
SavedStateHandle.remove(key)не очищал состоянияSavedStateHandle.getMutableStateFlow(key). ( d5f939 , b/418746333 )
Версия 2.9.0
7 мая 2025 г.
Выпущен androidx.lifecycle:lifecycle-*:2.9.0 . Версия 2.9.0 содержит следующие коммиты .
Важные изменения по сравнению с версией 2.8.0
- Доступен новый артефакт KMP
androidx.lifecycle:lifecycle-viewmodel-testing, который предоставляет классViewModelScenarioдля тестированияViewModelsв изоляции с поддержкойonClearedиSavedStateHandle, а также тестирование завершения и восстановления процесса с помощьюrecreate(). - Добавьте
getMutableStateFlowкSavedStateHandle, чтобы возвращатьMutableStateFlow. Эта новая функция является ключевой и не может использоваться сgetLiveData. При попытке использовать обе функции для доступа к одному и тому же состоянию будет выдано исключение. -
CreationExtrasтеперь включает перегрузки операторов, подобных картам, для идиоматической манипуляции содержимым в Kotlin. Это позволяет использоватьin,+=и+сCreationExtras.
Поддержка сериализации KotlinX
Благодаря поддержке сериализации KotlinX, добавленной в SavedState
1.3.0, мы добавили ленивый делегат свойствsaved, который упрощает сохранение классов@SerializableвSavedStateHandleи позволяет автоматически восстанавливать эти классы при завершении и восстановлении процесса. Обратите внимание, чтоsavedделегат является ленивым и не будет вызывать лямбда-функциюinitи сохранять данные вSavedStateHandleдо тех пор, пока к нему не будет выполнено обращение.@Serializable data class Person(val firstName: String, val lastName: String) class MyViewModel(handle: SavedStateHandle) : ViewModel() { var person by handle.saved { Person("John", "Doe") } fun onPersonChanged(person: Person) { this.person = person } }
Kotlin Мультиплатформенный
- Модуль
lifecycle-testingтеперь совместим с KMP, включая такие API, какTestLifecycleOwner. - Модуль
lifecycle-viewmodel-savedstateтеперь совместим с KMP, включая такие API, какSavedStateHandle. -
androidx.compose.ui.platform.LocalLifecycleOwnerтеперь доступен в общем исходном наборе. -
NewInstanceFactoryтеперь доступен на платформах JVM Desktop и Android.
Изменения поведения
- Состояние
Lifecycle.DESTROYEDявляется конечным, и любая попытка перевестиLifecycleиз него в любое другое состояние теперь приведет к исключениюIllegalStateException. -
SavedStateHandleбольше не включаетSavedStateProvider.saveState()если возвращаемыйBundleпуст.
Версия 2.9.0-rc01
23 апреля 2025 г.
Выпущен androidx.lifecycle:lifecycle-*:2.9.0-rc01 . Версия 2.9.0-rc01 содержит следующие коммиты .
Предупреждение о совместимости Lint API
- JetBrains изменила класс
KaCallableMemberCallна интерфейс , что нарушает бинарную совместимость. Это может привести к сбоям, если версия AGP вашего проекта отличается от версии, используемой для компиляции lint-проверок. Это обновление было внесено в aosp/3577172 , но отсутствовало в примечаниях к выпуску — мы уточняем это здесь. Рекомендуемое исправление: обновите AGP до последней стабильной версии. Если полное обновление невозможно, используйтеandroid.experimental.lint.versionдля согласования lint-проверок с вашей версией AGP — подробности см. в разделе «Изменения поведения среды выполнения Compose» .
Версия 2.9.0-beta01
9 апреля 2025 г.
Выпущен androidx.lifecycle:lifecycle-*:2.9.0-beta01 . Версия 2.9.0-beta01 содержит следующие коммиты .
Изменения API
-
Lifecycle ViewModel Composeтеперь использует ту же конфигурацию Kotlin Multiplatform, что и Compose Runtime 1.7.1 и более поздние версии: артефакты-desktopудалены, а артефакты-jvmStubsи-linuxx64Stubsдобавлены. Ни один из этих целевых объектов не предназначен для использования, они являются заглушками, помогающими работе Jetbrains Compose. ( I5cb14 , b/406592090 )
Обновления зависимостей
- Эта библиотека теперь ориентирована на уровень языка Kotlin 2.0 и требует KGP 2.0.0 или более поздней версии. ( Idb6b5 )
-
Lifecycle ViewModel Composeтеперь зависит от Compose 1.7.8. ( I5cb14 , b/406592090 )
Версия 2.9.0-альфа13
26 марта 2025 г.
androidx.lifecycle:lifecycle-*:2.9.0-alpha13 выпущен без заметных публичных изменений. Версия 2.9.0-alpha13 содержит следующие коммиты .
Версия 2.9.0-альфа12
12 марта 2025 г.
Выпущен androidx.lifecycle:lifecycle-*:2.9.0-alpha12 . Версия 2.9.0-alpha12 содержит следующие коммиты .
Изменения API
- Добавьте аннотацию
@MainThreadвViewModelProvider.getна всех поддерживаемых платформах KMP. ( I7e8dd , b/397736115 ) - Переименуйте
SavedState*DelegatesвSavedState*Delegate. ( I8589b , b/399629301 )
Версия 2.9.0-альфа11
26 февраля 2025 г.
Выпущен androidx.lifecycle:lifecycle-*:2.9.0-alpha11 . Версия 2.9.0-alpha11 содержит следующие коммиты .
Изменения API
- Добавить параметр
SavedStateConfigк делегатамsaved()( I39b3a )
Версия 2.9.0-альфа10
12 февраля 2025 г.
Выпущен androidx.lifecycle:lifecycle-*:2.9.0-alpha10 . Версия 2.9.0-alpha10 содержит следующие коммиты .
Изменения API
- Переместить
MutableStateSerializerвsavedstate-composeизlifecycle-viewmodel-compose. ( I4f690 , b/378895074 )
Внешний вклад
- Добавляет новую проблему Lint для вызова
Lifecycle::currentStateв композиции, предлагая вместо этого использоватьcurrentStateAsalue().value, чтобы гарантировать, что изменения в состоянии жизненного цикла корректно вызывают перекомпозицию. Спасибо, Стивен Шен! ( Iad484 )
Версия 2.9.0-альфа09
29 января 2025 г.
Выпущена androidx.lifecycle:lifecycle-*:2.9.0-alpha09 . Версия 2.9.0-alpha09 содержит следующие коммиты .
Новые функции
- Добавить
MutableStateSerializerдля сериализацииandroidx.compose.runtime.MutableState. ( Idfc48 , b/378895074 )
Изменения API
- Заменить перегруженные функции делегата
SavedStateHandle.saved()параметрами по умолчанию ( Icd1c1 ) -
AbstractSavedStateViewModelFactoryустарел, так как он создаётSavedStateHandleдля каждойViewModel, что приводит к ненужным накладным расходам. Для более эффективного созданияViewModelиспользуйтеViewModelProvider.FactoryсCreationExtras.createSavedStateHandle. ( Ia920b , b/388590327 ).
Версия 2.9.0-альфа08
11 декабря 2024 г.
Выпущена androidx.lifecycle:lifecycle-*:2.9.0-alpha08 . Версия 2.9.0-alpha08 содержит следующие коммиты .
Новые функции
- Добавьте
ViewModelScenario.recreateдля имитации завершения системного процесса, воссоздающего тестируемуюViewModelи все связанные с ней компоненты. ( Id6a69 , b/381063087 ) - Экземпляры
LifecycleOwnerиViewModelStoreOwner, полученные через соответствующие APIfindViewTree, теперь могут быть разрешены через непересекающиеся родительские элементы представления, такие какViewOverlay. Подробнее о непересекающихся родительских элементах представления см. в примечаниях к выпуску ядра или в документации поViewTree.setViewTreeDisjointParent. ( I800f4 ).
Изменения API
- Сделать наименования и организацию пакетов более согласованными с
SavedStateRegistryOwnerDelegate( I8c135 , b/376026744 )
Исправления ошибок
- Эта библиотека теперь использует аннотации JSpecify, определяющие значение null , которые являются типовыми. Разработчикам Kotlin следует использовать следующий аргумент компилятора для обеспечения корректного использования:
-Xjspecify-annotations=strict(это значение по умолчанию, начиная с версии 2.1.0 компилятора Kotlin). ( Ie4340 , b/326456246 ) - Последовательность очистки Document
ViewModel.onCleared. ( I586c7 , b/363984116 )
Версия 2.9.0-альфа07
13 ноября 2024 г.
Выпущен androidx.lifecycle:lifecycle-*:2.9.0-alpha07 . Версия 2.9.0-alpha07 содержит следующие коммиты .
Совместимость с Kotlin на разных платформах
- Lifecycle
ViewModel SavedStateтеперь совместим с KMP. Это позволяет использоватьSavedStateHandleв общем коде. ( Ib6394 , b/334076622 )
Поддержка сериализации KotlinX
Благодаря поддержке сериализации KotlinX, добавленной в SavedState
1.3.0-alpha05, мы добавили ленивый делегат свойствsaved, который упрощает сохранение классов@SerializableвSavedStateHandleи позволяет автоматически восстанавливать эти классы при завершении и восстановлении процесса. Обратите внимание, чтоsavedделегат является ленивым и не будет вызывать лямбда-функциюinitи сохранять что-либо вSavedStateHandleдо тех пор, пока к нему не будет получен доступ. ( I47a88 , b/376026744 )@Serializable data class Person(val firstName: String, val lastName: String) class MyViewModel(handle: SavedStateHandle) : ViewModel() { var person by handle.saved { Person("John", "Doe") } fun onPersonChanged(person: Person) { this.person = person } }
Изменения API
- Добавьте
getMutableStateFlowкSavedStateHandle, чтобы возвращатьMutableStateFlow. Эта новая функция является ключевой и не может использоваться сgetLiveData. При попытке использовать обе функции для доступа к одному и тому же состоянию будет выдано исключение. ( I04a4f , b/375408415 )
Версия 2.9.0-альфа06
30 октября 2024 г.
Выпущена androidx.lifecycle:lifecycle-*:2.9.0-alpha06 . Версия 2.9.0-alpha06 содержит следующие коммиты .
Изменения поведения
- Состояние
Lifecycle.DESTROYEDявляется конечным, и любая попытка перевестиLifecycleиз него в любое другое состояние теперь приведет к исключениюIllegalStateException. ( I116c4 , b/370577987 ) -
SavedStateHandleбольше не включаетSavedStateProvider.saveState(), если возвращаемыйBundleпуст. ( I910b5 , b/370577987 )
Исправления ошибок
-
Lifecycle.eventFlowтеперь корректно завершается, когдаLifecycleDESTROYED( I293b2 , b/374043130 )
Версия 2.9.0-альфа05
16 октября 2024 г.
androidx.lifecycle:lifecycle-*:2.9.0-alpha05 выпущен без существенных изменений. Версия 2.9.0-alpha05 содержит следующие коммиты .
Версия 2.9.0-альфа04
2 октября 2024 г.
Выпущен androidx.lifecycle:lifecycle-*:2.9.0-alpha04 . Версия 2.9.0-alpha04 содержит следующие коммиты .
Kotlin Мультиплатформенный
- Модуль
lifecycle-viewmodel-savedstateтеперь настроен на совместимость с KMP в рамках подготовки к тому, что такие API, какSavedStateHandle, станут доступны в общем исходном наборе в будущем выпуске. ( I503ed , I48764 , b/334076622 )
Версия 2.9.0-альфа03
18 сентября 2024 г.
Выпущена androidx.lifecycle:lifecycle-*:2.9.0-alpha03 . Версия 2.9.0-alpha03 содержит следующие коммиты .
Исправления ошибок
- Начиная с Lifecycle
2.8.6: ошибкаNullSafeMutableLiveDataLint улучшила поддержку смарт-приведений, избегая ложных срабатываний. ( 85fed6 , b/181042665 )
Обновления зависимостей
- Начиная с Lifecycle
2.8.6: Lifecycle Runtime Compose теперь зависит от Compose Runtime1.7.1 - Lifecycle Runtime теперь зависит от ProfileInstaller
1.4.0
Версия 2.9.0-альфа02
4 сентября 2024 г.
Выпущен androidx.lifecycle:lifecycle-*:2.9.0-alpha02 . Версия 2.9.0-alpha02 содержит следующие коммиты .
Исправления ошибок
- Начиная с Lifecycle
2.8.5: обновите правилаandroidx.lifecycle.ReportFragmentProGuard, чтобы разрешить обфускацию. ( ff898e1 )
Внешний вклад
- Перенести
androidx.compose.ui.platform.LocalLifecycleOwnerв общий исходный набор (KMP). Благодарим Ивана Маткова из JetBrains за вклад. ( 8cd5d03 ) - Начиная с версии Lifecycle
2.8.5: делегат расширения SavedStateHandle.saveable теперь поддерживает значения, допускающие NULL. Благодарим Романа Калукевича за вклад. ( 0d78ea6 )
Версия 2.9.0-альфа01
7 августа 2024 г.
Выпущен androidx.lifecycle:lifecycle-*:2.9.0-alpha01 . Версия 2.9.0-alpha01 содержит следующие коммиты .
Kotlin Мультиплатформенный
-
lifecycle-testingтеперь совместимо с KMP. ( Iea41e ) - Добавить поддержку многоплатформенной цели
linuxArm64kotlin ( I139d3 , b/338268719 )
Новые функции
- Доступен новый артефакт KMP
androidx.lifecycle:lifecycle-viewmodel-testing, который предоставляет классViewModelScenarioдля изолированного тестирования ViewModels с поддержкойonCleared(все платформы) иSavedStateHandle(только Android). ( 337f68d , c9b3409 , 9799a95c , b/264602919 ) - Создание
ViewModelс помощьюViewModelProviderтеперь потокобезопасно; аннотации@MainThreadбыли удалены. ( Ifd978 , b/237006831 )
Изменения API
- Добавьте фабричную функцию
CreationExtras.Key()для упрощения создания анонимных объектовCreationExtras.Key. ( I970ee ) -
CreationExtrasтеперь включает перегрузки операторов, подобных картам, для идиоматической манипуляции содержимым в Kotlin. Это позволяет использоватьin,+=и+сCreationExtras. ( Ib4353 ) -
CreationExtrasтеперь реализует методыequals,hashCodeиtoString. ( Ib4353 ) -
NewInstanceFactoryтеперь доступен на платформах JVM Desktop и Android. ( d3d0892 ) - Встроенное свойство расширения для безопасного предоставления базового приложения в версии языка Kotlin 2.0 ( I39df2 )
Исправления ошибок
- Удалено ручное описание доступа к новым API платформы, поскольку это происходит автоматически посредством моделирования API при использовании R8 с AGP 7.3 или более поздней версии (например, R8 версии 3.3) и для всех сборок с использованием AGP 8.1 или более поздней версии (например, D8 версии 8.1). Клиентам, не использующим AGP, рекомендуется обновиться до D8 версии 8.1 или более поздней. Подробнее см. в этой статье . ( If6b4c , b/345472586 )
Версия 2.8
Версия 2.8.7
30 октября 2024 г.
Выпущен androidx.lifecycle:lifecycle-*:2.8.7 . Версия 2.8.7 содержит следующие коммиты .
Изменения API
-
androidx.compose.ui.platform.LocalLifecycleOwnerтеперь доступен в общем исходном наборе (KMP). ( 6a3f5b3 ) -
lifecycle-runtime-compose: артефактыdesktopбыли удалены, а артефакты-jvmStubsи-linuxx64Stubsбыли добавлены. Ни один из этих целевых объектов не предназначен для использования, они являются заглушками, помогающими работе Jetbrains Compose. ( 6a3f5b3 )
Версия 2.8.6
18 сентября 2024 г.
Выпущен androidx.lifecycle:lifecycle-*:2.8.6 . Версия 2.8.6 содержит следующие коммиты .
Исправления ошибок
- Ошибка
NullSafeMutableLiveDataLint улучшила поддержку смарт-приведений, избегая ложных срабатываний. ( 85fed6 , b/181042665 )
Обновления зависимостей
- Lifecycle Runtime Compose теперь зависит от Compose Runtime
1.7.1
Версия 2.8.5
4 сентября 2024 г.
Выпущен androidx.lifecycle:lifecycle-*:2.8.5 . Версия 2.8.5 содержит следующие коммиты .
Исправления ошибок
- Обновите правила
androidx.lifecycle.ReportFragmentProGuard, чтобы разрешить обфускацию. ( ff898e1 )
Внешний вклад
- Делегат расширения
SavedStateHandle.saveableтеперь поддерживает значения, допускающие NULL. Спасибо Роману Калукевичу за вклад. ( 0d78ea6 )
Версия 2.8.4
24 июля 2024 г.
Выпущен androidx.lifecycle:lifecycle-*:2.8.4 . Версия 2.8.4 содержит следующие коммиты .
Исправления ошибок
-
LiveData.asFlow()теперь корректно обрабатывает случаи, когда возвращаемый поток немедленно завершается после получения значения, уже установленного вLiveData(например, при использованииtake(1)). ( I9c566 ) - Завершение
Lifecycle*Effectтеперь идемпотентно (т. е. еслиonStopOrDisposeбыл вызван из-за остановки жизненного цикла, он не будет вызван повторно при завершении, если только жизненный цикл снова не вернется в состояниеSTARTED). ( I5f607 , b/352364595 )
Версия 2.8.3
1 июля 2024 г.
Выпущен androidx.lifecycle:lifecycle-*:2.8.3 . Версия 2.8.3 содержит следующие коммиты .
Исправления ошибок
- Исправлена проблема обратной совместимости Lifecycle 2.8 с Compose 1.6.0 и более ранними версиями при использовании сжатия кода. ( aosp/3133056 , b/346808608 )
Версия 2.8.2
12 июня 2024 г.
Выпущен androidx.lifecycle:lifecycle-*:2.8.2 . Версия 2.8.2 содержит следующие коммиты .
Исправления ошибок
- Исправлена ошибка
CompositionLocal LocalLifecycleOwner not presentошибок при использовании Lifecycle 2.8.X с Compose 1.6.X или более ранней версии. Теперь вы можете использовать Lifecycle 2.8.2 с любой версией Compose без необходимости каких-либо обходных путей. ( aosp/3105647 , b/336842920 ) -
ViewModelProviderбольше не будет давать сбой при смешивании предыдущих версий зависимостейcompileOnlyLifecycle с версиями 2.8+, что устраняет проблемы с такими библиотеками, как LeakCanary. ( I80383 , b/341792251 )
Версия 2.8.1
29 мая 2024 г.
Выпущен androidx.lifecycle:lifecycle-*:2.8.1 . Версия 2.8.1 содержит следующие коммиты .
Исправления ошибок
-
lifecycle-viewmodel-composeтеперь имеет только общую зависимость отcompose-runtime, что устраняет его общую зависимость отcompose-ui. Артефакт Android сохраняет свойcompose-uiдля совместимости. ( aosp/3079334 , b/339562627 ) -
saveableинтеграцияViewModelс использованием делегатов свойств теперь использует имя класса как часть автоматически сгенерированного ключа, избегая конфликтов, если несколько классов используют один и тот жеSavedStateHandle. ( aosp/3063463 )
Версия 2.8.0
14 мая 2024 г.
Выпущен androidx.lifecycle:lifecycle-*:2.8.0 . Версия 2.8.0 содержит следующие коммиты .
Важные изменения по сравнению с версией 2.7.0
-
LocalLifecycleOwnerбыл перемещен из Compose UI вlifecycle-runtime-composeчтобы его вспомогательные API на основе Compose можно было использовать за пределами Compose UI. - Артефакт
lifecycle-runtime-composeтеперь содержит APIdropUnlessResumedиdropUnlessStarted, которые позволяют отменять события щелчков или другие события, происходящие даже после того, какLifecycleOwnerопустился ниже заданного значенияLifecycle.State. Например, это можно использовать с Navigation Compose, чтобы избежать обработки событий щелчков после начала перехода на другой экран:onClick: () -> Unit = dropUnlessResumed { navController.navigate(NEW_SCREEN) } ViewModel.viewModelScopeтеперь является переопределяемым параметром конструктора, что позволяет вам внедрять собственный диспетчер иSupervisorJob()или переопределять значения по умолчанию, используяbackgroundScope, доступный вrunTest. ( I2817c , b/264598574 )class MyViewModel( // Make Dispatchers.Main the default, rather than Dispatchers.Main.immediate viewModelScope: CoroutineScope = Dispatchers.Main + SupervisorJob() ) : ViewModel(viewModelScope) { // Use viewModelScope as before, without any code changes } // Allows overriding the viewModelScope in a test fun Test() = runTest { val viewModel = MyViewModel(backgroundScope) }ViewModelбыл переписан на Kotlin и теперь используетAutoClosableвместоCloseable. Теперь он поддерживает добавление объектовAutoCloseableсkey, позволяющим получать их черезgetCloseable().Вызов
LifecycleStartEffectиLifecycleResumeEffectбез ключа теперь является ошибкой в соответствии с тем же соглашением, что и APIDisposableEffect, которое отражают эти API.LiveDataReactiveStreams.toPublisher(lifecycleOwner, liveData)устарел и заменен наLiveData.toPublisher(lifecycleOwner).Расширения kotlin
lifecycle-livedata-core-ktxтеперь перенесены в модульlifecycle-livedata-core.NullSafeMutableLiveDataбыл переработан, чтобы избежать множества ложных срабатываний.
Совместимость жизненного цикла Kotlin с несколькими платформами
Основные API жизненного цикла в Lifecycle , LifecycleOwner , LifecycleObserver , Lifecycle.State , Lifecycle.Event и LifecycleRegistry теперь поставляются в артефактах, совместимых с Kotlin Multiplatform.
Затронутые артефакты:
-
lifecycle-commonпереводит большинство API вcommonи поддерживает jvm и iOS в дополнение к Android. -
lifecycle-runtimeпереводит большинство API вcommonи поддерживает jvm и iOS в дополнение к Android. -
lifecycle-runtime-ktxтеперь пуст, все API перемещены вlifecycle-runtime. -
lifecycle-runtime-composeперемещает все API вcommonи поставляет артефакт Android, соответствующий многоплатформенной поддержкеandroidx.compose.
Совместимость ViewModel Kotlin с различными платформами
Артефакт lifecycle-viewmodel и такие API, как ViewModel , ViewModelStore , ViewModelStoreOwner и ViewModelProvider , теперь поставляются в артефактах, совместимых с Kotlin Multiplatform.
Чтобы учесть это изменение, методы, подобные методам ViewModelProvider , которые принимали java.lang.Class<T> теперь имеют эквивалентный метод, который принимает kotlin.reflect.KClass<T> .
Бинарная совместимость на Android сохранена, но есть несколько заметных изменений при сравнении поверхности API Android с поверхностью общего API:
- Создание экземпляра
ViewModelProviderтеперь выполняется с помощью методовViewModelProvider.create(), а не путем прямого вызова его конструктора. -
ViewModelProvider.NewInstanceFactoryиViewModelProvider.AndroidViewModelFactoryдоступны только на Android.- Рекомендуется, чтобы пользовательские фабрики расширяли
ViewModelProvider.Factoryи использовали методcreate, который принимаетCreationExtras, или использовалиviewModelFactoryKotlin DSL.
- Рекомендуется, чтобы пользовательские фабрики расширяли
- Использование
ViewModelProviderбез пользовательской фабрики на платформах, отличных от JVM, приведёт к исключениюUnsupportedOperationException. На платформах JVM совместимость сохраняется благодаря использованию конструктора ViewModel без аргументов, если пользовательская фабрика не предоставлена. -
viewModelScopeбудет возвращаться кEmptyCoroutineContextна платформах, гдеDispatchers.Mainнедоступен (например, Linux).
Затронутые артефакты:
-
lifecycle-viewmodelпереводит большинство API вcommonи поддерживает jvm и iOS в дополнение к Android. -
lifecycle-viewmodel-ktxтеперь пуст, все API перемещены вlifecycle-viewmodel. -
lifecycle-viewmodel-composeперемещает все API вcommonи поставляет артефакт Android, соответствующий многоплатформенной поддержкеandroidx.compose.
Изменения поведения
-
InitializerViewModelFactory(включая функцию конструктораviewModelFactory) теперь будет выдавать исключениеIllegalArgumentException, еслиinitializerс тем жеclazz: KClass<VM : ViewModel>уже был добавлен. ( Ic3a36 )
Известные проблемы
-
lifecycle-*:2.8.0требует версию Compose не ниже 1.7.0-alpha05 ( b/336842920 ).
Версия 2.8.0-rc01
1 мая 2024 г.
Выпущена androidx.lifecycle:lifecycle-*:2.8.0-rc01 . Версия 2.8.0-rc01 содержит следующие коммиты .
Исправления ошибок
- Исправлена ошибка, из-за которой базовый профиль для
lifecycle-commonне был должным образом упакован. Теперь они упакованы в AAR-файлlifecycle-runtime. ( aosp/3038274 , b/322382422 ) - Исправлено непреднамеренное изменение порядка очистки экземпляров
AutoCloseable, прикрепленных к ViewModel. Восстановлен предыдущий порядок:addCloseable(String, AutoCloseable), затемaddClosable(AutoCloseable), затемonCleared(). ( aosp/3041632 ) - Улучшить поведение создания по умолчанию для
viewModelScopeдля собственных сред и сред JVM Desktop. ( aosp/3039221 )
Внешний вклад
- Спасибо Виктору Кроппу за улучшение проверки основного потока на JVM Desktop. ( aosp/3037116 )
Версия 2.8.0-beta01
17 апреля 2024 г.
Выпущен androidx.lifecycle:lifecycle-*:2.8.0-beta01 . Версия 2.8.0-beta01 содержит следующие коммиты .
Новые функции
- Артефакт
lifecycle-runtime-composeтеперь совместим с Kotlin Multiplatform, его код перемещен вcommonи поставляется с артефактом Android, что соответствует поддержке нескольких платформ дляandroidx.compose. ( If7a71 , I4f4a0 , b/331769623 )
Версия 2.8.0-альфа04
3 апреля 2024 г.
Выпущен androidx.lifecycle:lifecycle-*:2.8.0-alpha04 . Версия 2.8.0-alpha04 содержит следующие коммиты .
Новые функции
- Артефакт
lifecycle-viewmodel-composeтеперь совместим с Kotlin Multiplatform, его код перенесён вcommonи поставляется как артефакт Android, что соответствует мультиплатформенной поддержкеandroidx.compose. Чтобы учесть это изменение, метод ComposableviewModelтеперь принимаетKClassв дополнение кjava.lang.Class. ( b/330323282 )
Исправления ошибок
-
NullSafeMutableLiveDataбыл рефакторингирован, чтобы избежать множества ложных срабатываний. ( I2d8c1 , Iafb18 , I03463 , I7ecef )
Обновление зависимости
- Артефакт
lifecycle-viewmodel-composeтеперь зависит от Compose 1.6.0. - Жизненный цикл теперь зависит от Profile Installer 1.3.1 .
Версия 2.8.0-альфа03
20 марта 2024 г.
Выпущен androidx.lifecycle:lifecycle-*:2.8.0-alpha03 . Версия 2.8.0-alpha03 содержит следующие коммиты .
Новые функции
ViewModel.viewModelScopeтеперь является переопределяемым параметром конструктора, что позволяет вам внедрять собственный диспетчер иSupervisorJob()или переопределять значения по умолчанию, используяbackgroundScope, доступный вrunTest. ( I2817c , b/264598574 )class MyViewModel( // Make Dispatchers.Main the default, rather than Dispatchers.Main.immediate viewModelScope: CoroutineScope = Dispatchers.Main + SupervisorJob() ) : ViewModel(viewModelScope) { // Use viewModelScope as before, without any code changes } // Allows overriding the viewModelScope in a test fun Test() = runTest { val viewModel = MyViewModel(backgroundScope) }
Совместимость с Kotlin на разных платформах
Артефакт lifecycle-viewmodel и такие API, как ViewModel , ViewModelStore , ViewModelStoreOwner и ViewModelProvider , теперь поставляются в артефактах, совместимых с Kotlin Multiplatform. ( b/214568825 )
Чтобы учесть это изменение, методы, подобные методам ViewModelProvider , которые принимали java.lang.Class<T> теперь имеют эквивалентный метод, который принимает kotlin.reflect.KClass<T> .
Бинарная совместимость на Android сохранена, но есть несколько заметных изменений при сравнении поверхности API Android с поверхностью общего API:
- Создание экземпляра
ViewModelProviderтеперь выполняется с помощью методовViewModelProvider.create(), а не путем прямого вызова его конструктора. -
ViewModelProvider.NewInstanceFactoryиViewModelProvider.AndroidViewModelFactoryдоступны только на Android.- Рекомендуется, чтобы пользовательские фабрики расширяли
ViewModelProvider.Factoryи использовали методcreate, который принимаетCreationExtras, или использовалиviewModelFactoryKotlin DSL.
- Рекомендуется, чтобы пользовательские фабрики расширяли
- Использование
ViewModelProviderбез пользовательской фабрики на платформах, отличных от JVM, приведёт к исключениюUnsupportedOperationException. На платформах JVM совместимость сохраняется благодаря использованию конструктора ViewModel без аргументов, если пользовательская фабрика не предоставлена. -
viewModelScopeбудет возвращаться кEmptyCoroutineContextна платформах, гдеDispatchers.Mainнедоступен (например, Linux).
Изменения поведения
-
InitializerViewModelFactory(включая функцию конструктораviewModelFactory) теперь будет выдавать исключениеIllegalArgumentException, еслиinitializerс тем жеclazz: KClass<VM : ViewModel>уже был добавлен. ( Ic3a36 )
Исправления ошибок
-
ViewModel.getCloseableтеперь обрабатывает дублирующиеся ключи: если сkeyуже связан ресурсAutoCloseable, старый ресурс будет заменен и немедленно закрыт. ( Ibeb67 ) - Доступ к
viewModelScopeобъектаViewModelтеперь потокобезопасен. ( If4766 , b/322407038 )
Внешний вклад
-
LocalLifecycleOwnerперенесён из Compose UI в lifecycle-runtime-compose, чтобы его вспомогательные API на основе Compose можно было использовать вне Compose UI. Спасибо Джейку Уортону за вклад. ( I6c41b , b/328263448 )
Версия 2.8.0-альфа02
21 февраля 2024 г.
Выпущена androidx.lifecycle:lifecycle-*:2.8.0-alpha02 . Версия 2.8.0-alpha02 содержит следующие коммиты.
Новые функции
- Добавлены API
dropUnlessResumedиdropUnlessStarted, позволяющие отменять события щелчков или другие события, происходящие даже после того, какLifecycleOwnerопустился ниже заданного значенияLifecycle.State. Например, это можно использовать с Navigation Compose, чтобы избежать обработки событий щелчков после перехода на другой экран:onClick: () -> Unit = dropUnlessResumed { navController.navigate(NEW_SCREEN) }( Icba83 , b/317230685 )
Конвертации Kotlin
-
ViewModelтеперь написан на Kotlin ( I16f26 , b/214568825 ) - Расширения
lifecycle-viewmodel-ktxдля Kotlin теперь перенесены в базовый модуль жизненного цикла. ( Id787b , b/274800183 ) - Расширения
lifecycle-runtime-ktxдля Kotlin теперь перенесены в базовый модуль жизненного цикла. ( Ic3686 , b/274800183 ) - Расширения
lifecycle-livedata-core-ktxдля Kotlin теперь перенесены в базовый модуль жизненного цикла. ( I54a3d , b/274800183 )
Совместимость с Kotlin на разных платформах
- Основные API жизненного цикла в
Lifecycle,LifecycleOwner,LifecycleObserver,Lifecycle.State,Lifecycle.EventиLifecycleRegistryтеперь поставляются в артефактах, совместимых с Kotlin Multiplatform. ( b/317249252 )
Изменения API
- Вызов
LifecycleStartEffectиLifecycleResumeEffectбез ключа теперь является ошибкой, следуя тому же соглашению, что и APIDisposableEffect, которое отражают эти API. ( Ib0e0c , b/323518079 ) -
ViewModelтеперь используетAutoCloseableвместоCloseable. Это изменение обратно совместимо. ( I27f8e , b/214568825 ) -
LiveDataReactiveStreams.toPublisher(lifecycleOwner, liveData)устарел и теперь используется методLiveData.toPublisher(lifecycleOwner). ( Iabe29 , b/262623005 )
Внешний вклад
- Благодарим Ивана Маткова из Jetbrains за помощь в переносе Lifecycle на Kotlin Multiplatform. ( aosp/2926690 , I0c5ac , If445d )
Версия 2.8.0-альфа01
24 января 2024 г.
Выпущена androidx.lifecycle:lifecycle-*:2.8.0-alpha01 . Версия 2.8.0-alpha01 содержит следующие коммиты.
Новые функции
-
ViewModelтеперь поддерживает добавление объектовCloseableсkey, который позволяет извлекать их черезgetCloseable(). ( I3cf63 )
Версия 2.7
Версия 2.7.0
10 января 2024 г.
Выпущен androidx.lifecycle:lifecycle-*:2.7.0 . Версия 2.7.0 содержит следующие коммиты.
Важные изменения по сравнению с версией 2.6.0
-
TestLifecycleOwnerтеперь включает функцию приостановкиsetCurrentState(), которая гарантирует, что изменение состояния и все обратные вызовыLifecycleObserverбудут завершены перед возвратом. Примечательно, что в отличие от прямой установки свойстваcurrentState, здесь не используетсяrunBlocking, что делает её безопасной для использования в сопрограмме, например, в сопрограммеrunTest. - Расширения
LiveDataдляmapиswitchMapтеперь отражают поведениеdistinctUntilChanged: еслиvalueLiveDataустановлено, функцияmap/switchMapбудет немедленно вызвана для заполнения возвращаемогоvalueLiveData. Это гарантирует, что начальное значение будет установлено как часть первой композиции (при использовании сobserveAsState()), но не меняет поведение наблюдения: обновлённые значения из исходногоLiveDataбудут применяться только после начала наблюденияLiveData. - В этом выпуске исправлена проблема, из-за которой
SavedStateHandleнекорректно восстанавливал пользовательские классыParcelableпосле завершения и повторного запуска процесса. Из-за потери информации о типах фреймворком Android массивы пользовательских Parcelable требуют дополнительных действий (ручного создания типизированного массива нужного типа), и в документации поget,getLiveDataиgetStateFlowэто ограничение теперь специально оговаривается. - The proguard keep rules associated with
LifecycleObserverhave been removed. This means that proguarded code that wishes to use APIs via reflection (such as using the long since deprecated@OnLifecycleEventannotation) will need to provide their own keep rules for their specific use case.
Lifecycle Event Observability
- As an alternative to using a
LifecycleEventObserver, you can now observe aFlowofLifecycle.Eventvia theLifecycle.asFlow()extension method. - Jetpack Compose users can now use
LifecycleEventEffectto run Compose side effects based onLifecycle.Event.
@Composable
fun HomeScreen(viewModel: HomeViewModel = viewModel()) {
LifecycleEventEffect(Lifecycle.Event.ON_RESUME) {
viewModel.refreshData()
}
// …
}
- Jetpack Compose users can use
LifecycleStartEffectandLifecycleResumeEffectto handle pairs of events - started to stopped and resumed to paused, respectively. This API mirrors the one found inDisposableEffectand is suitable for cases where the change being made when the state is going up needs to be reversed when going back down.
fun HomeScreen(viewModel: HomeViewModel = viewModel()) {
LifecycleStartEffect(viewModel) {
val timeTracking = viewModel.startTrackingTimeOnScreen()
onStopOrDispose {
timeTracking.stopTrackingTimeOnScreen()
}
}
// …
}
See Run code on lifecycle events for more information.
Lifecycle State Observability
- The current
Lifecycle.Statecan now be observed via theLifecycle.currentStateFlowproperty, which returns aStateFlowwhere thevalueis the currentLifecycle.State. - Jetpack Compose users can use the
Lifecycle.currentStateAsState()extension to directly exposeLifecycle.Stateas ComposeState. This is equivalent (and a shorter alternative) tolifecycle.currentStateFlow.collectAsState().
See Collect lifecycle state with flows for more information.
Версия 2.7.0-rc02
13 декабря 2023 г.
androidx.lifecycle:lifecycle-*:2.7.0-rc02 is released. Version 2.7.0-rc02 contains these commits.
Исправления ошибок
- Fixed an issue where
SavedStateHandlewould not properly restore customParcelableclasses after process death and recreation. Due to type information that is lost by the Android framework, arrays of custom Parcelables require additional work (manually creating a typed array of the right type) and the documentation onget,getLiveData, andgetStateFlownow specifically calls this limitation out. ( I0b55a )
Версия 2.7.0-rc01
15 ноября 2023 г.
androidx.lifecycle:lifecycle-*:2.7.0-rc01 is released. Version 2.7.0-rc01 contains these commits.
Исправления ошибок
-
LifecycleStartEffectandLifecycleResumeEffectnow correctly dispose and recreate the effect block if theLifecycleOwneris changed. ( Ia25c6 )
Версия 2.7.0-beta01
1 ноября 2023 г.
androidx.lifecycle:lifecycle-*:2.7.0-beta01 is released with no changes. Version 2.7.0-beta01 contains these commits.
- A beta version bump, no major changes to this release version.
Версия 2.7.0-альфа03
18 октября 2023 г.
androidx.lifecycle:lifecycle-*:2.7.0-alpha03 is released. Version 2.7.0-alpha03 contains these commits.
Новые функции
-
lifecycle-runtime-testingnow contains a new Lint check to avoid setting theLifecycle.Stateof theTestLifecycleOwnerby using thecurrentStatefield when inside of a coroutine. The Lint check now suggests the suspendingsetCurrentStatewhich allows setting theLifecycle.Statewithout blocking. ( Icf728 , b/297880630 )
Исправления ошибок
- Fixed an issue with
LiveData.switchMapwhere returning the sameLiveDatainstance both on the initial call and a subsequent call would prevent theLiveDatainstance from being added as a source. ( Ibedcba7 )
Версия 2.7.0-альфа02
6 сентября 2023 г.
androidx.lifecycle:lifecycle-*:2.7.0-alpha02 is released. Version 2.7.0-alpha02 contains these commits.
Новые функции
-
TestLifecycleOwnernow includes the suspending functionsetCurrentState()to give users the option of usingTestLifecycleOwnerfrom within a coroutine such as one provided byrunTest. ( I329de , b/259344129 )
Изменения API
- All files from the
lifecycle-livedata-ktxmodules have been moved into the mainlifecycle-livedatamodule. ( I10c6f , b/274800183 )
Изменения поведения
- The
LiveData.map()andLiveData.switchMap()extensions now sets thevalueof the returnedLiveDataif the previousLiveDatahas had a value set on it, ensuring that using the resulting LiveData in Jetpack Compose has the right state on the initial composition. ( I91d2b , b/269479952 ) -
ViewModel'saddCloseable()now immediately closes theCloseableif theViewModelhas already received a call toonCleared(). ( I4712e , b/280294730 )
Исправления ошибок
- From Lifecycle
2.6.2: Fixed an issue whereSavedStateHandlewould not correctly be restored after process death if the state was restored,save()was called without actually saving the state in the parentSavedStateRegistry, and then the state was restored again. This fixes the interaction betweenrememberSaveableand Navigation Compose'sNavHost. ( aosp/2729289 )
Версия 2.7.0-альфа01
26 июля 2023 г.
androidx.lifecycle:lifecycle-*:2.7.0-alpha01 is released. Version 2.7.0-alpha01 contains these commits.
Изменения API
-
Lifecycle.Stateis now Compose-observable viaLifecycle.currentStateFlow, which returns aStateFlowwhere thevalueis the currentLifecycle.State. ( Ib212d , b/209684871 ) -
Lifecycle.Events can now able to be observed as aFlowwithLifecycle.asFlow().( If2c0f , b/176311030 ) -
LifecycleResumeEffectAPI has been added to run ComposeSideEffects based on bothLifecycle.Event.ON_RESUMEandLifecycle.Event.ON_PAUSEevent callbacks. ( I60386 , b/235529345 ) -
LifecycleStartEffectAPI has been added to run ComposeSideEffects based onLifecycle.Event.ON_STARTandLifecycle.Event.ON_STOPevent callbacks. ( I5a8d1 , b/235529345 ) -
LifecycleEventEffectAPI has been added to run ComposeSideEffects based onLifecycle.Event. ( Ic9794 , b/235529345 ) -
Lifecycle.collectAsState()extension has been added to directly exposeLifecycle.Stateas ComposeState. This is equivalent (and a shorter alternative) tolifecycle.currentStateFlow.collectAsState(). ( I11015 , b/235529345 )
Исправления ошибок
- The
LiveData.distinctUntilChanged()extension now sets thevalueof the returnedLiveDataif the previousLiveDatahas had a value set on it. This does not change the observation behavior - updated values from the sourceLiveDatawill still only apply once you start observing theLiveDatareturned fromdistinctUntilChanged(). ( Ib482f ) - The proguard keep rules associated with
LifecycleObserverhave been removed. This means that proguarded code that wishes to use APIs via reflection will need to provide their own keep rules for their specific use case. ( Ia12fd )
Версия 2.6
Версия 2.6.2
6 сентября 2023 г.
androidx.lifecycle:lifecycle-*:2.6.2 is released. Version 2.6.2 contains these commits.
Исправления ошибок
- Fixed an issue where
SavedStateHandlewould not correctly be restored after process death if the state was restored,save()was called without actually saving the state in the parentSavedStateRegistry, and then the state was restored again. This fixes the interaction betweenrememberSaveableand Navigation Compose'sNavHost. ( aosp/2729289 )
Версия 2.6.1
22 марта 2023 г.
androidx.lifecycle:lifecycle-*:2.6.1 is released. Version 2.6.1 contains these commits.
Обновления зависимостей
-
lifecycle-viewmodel-savedstatenow depends on SavedState1.2.1. ( cd7251 ) - Lifecycle now depends on ProfileInstaller
1.3.0. ( f9d30b )
Версия 2.6.0
8 марта 2023 г.
androidx.lifecycle:lifecycle-*:2.6.0 is released. Version 2.6.0 contains these commits.
Important changes since 2.5.0
-
LiveDatanow includes a newisInitializedproperty that indicates whether an explicit value has ever been set on theLiveData, allowing you to distinguish betweenliveData.valuereturningnullbecause no value has ever been set or an explicitnullvalue. -
MediatorLiveDatanow includes a constructor to set an initial value. - Added a new extension on
StateFlowandFlowofcollectAsStateWithLifecycle()that collect from flows and represents its latest value as Compose State in a lifecycle-aware manner. -
Lifecycle.launchWhenXmethods andLifecycle.whenXmethods have been deprecated as the use of a pausing dispatcher can lead to wasted resources in some cases. It is recommended to useLifecycle.repeatOnLifecycle. For more information about one-time suspending work, please see this explanation on why this is inherently unsafe. - Kotlin Conversion - A large number of Lifecycle classes have been converted to Kotlin. All converted classes still retain their binary compatibility with previous versions. The following classes have source incompatible changes for classes written in Kotlin:
ViewTreeLifecycleOwner,LiveDataReactiveStreams,HasDefaultViewModelProviderFactory,ViewTreeViewModelStoreOwner,Transformations,ViewModelStoreOwner,LifecycleOwner
The table below provides the source conversions for the new version of lifecycle.
| Lifecycle 2.5 | Lifecycle 2.5 (KTX) | Lifecycle 2.6 |
|---|---|---|
Transformations.switchMap(liveData) {...} | liveData.switchMap {...} | liveData.switchMap {...} |
Transformations.map(liveData) {...} | liveData.map {...} | liveData.map {...} |
Transformations.distinctUntilChanged(liveData) {...} | liveData.distinctUntilChanged{...} | liveData.distinctUntilChanged{...} |
LiveDataReactiveStreams.fromPublisher(publisher) | publisher.toLiveData() | publisher.toLiveData() |
LiveDataReactiveStreams.toPublisher(lifecycleOwner, liveData) | liveData.toPublisher(lifecycleOwner) | liveData.toPublisher(lifecycleOwner) |
override fun getDefaultViewModelProviderFactory(): ViewModelProvider.Factory = factory | override fun getDefaultViewModelProviderFactory(): ViewModelProvider.Factory = factory | override val defaultViewModelProviderFactory = factory |
override fun getDefaultViewModelCreationExtras(): CreationExtras = extras | override fun getDefaultViewModelCreationExtras(): CreationExtras = extras | override val defaultViewModelProviderCreationExtras = extras |
ViewTreeLifecycleOwner.set(view, owner) | ViewTreeLifecycleOwner.set(view, owner) | view.setViewTreeLifecycleOwner(owner) |
ViewTreeLifecycleOwner.get(view) | view.findViewTreeLifecycleOwner() | view.findViewTreeLifecycleOwner() |
override fun getViewModelStore(): ViewModelStore = store | override fun getViewModelStore(): ViewModelStore = store | override val viewModelStore: ViewModelStore = store |
override fun getLifecycle(): Lifecycle = registry | override fun getLifecycle(): Lifecycle = registry | override val lifecycle: Lifecycle get() = registry |
- The nullability of the
onChangedmethod of aObservercreated in Kotlin now matches the nullability of the generic type. If you wantObserver.onChanged()to accept a nullable type, you must instantiate theObserverwith a nullable type. - These classes were also converted to Kotlin, but remain source compatible:
DefaultLifecycleObserver,LifecycleEventObserver,Lifecycle,LifecycleRegistry,LifecycleObserver,ViewModelStore,AndroidViewModel,AbstractSavedStateViewModelFactory,LifecycleService,ServiceLifecycleDispatcher, andProcessLifecycleOwner
Версия 2.6.0-rc01
22 февраля 2023 г.
androidx.lifecycle:lifecycle-*:2.6.0-rc01 is released. Version 2.6.0-rc01 contains these commits.
Исправления ошибок
- The
LiveData.distinctUntilChanged()extension now sets thevalueof the returnedLiveDataif the previousLiveDatahas had a value set on it. This does not change the observation behavior - updated values from the sourceLiveDatawill still only apply once you start observing theLiveDatareturned fromdistinctUntilChanged(). ( Ib482f )
Версия 2.6.0-beta01
8 февраля 2023 г.
androidx.lifecycle:lifecycle-*:2.6.0-beta01 is released. Version 2.6.0-beta01 contains these commits.
Kotlin Conversions
-
LifecycleOwneris now written in Kotlin. This is a source incompatible change for classes written in Kotlin - they must now override thelifecycleproperty rather than implementing the previousgetLifecycle()function. ( I75b4b , b/240298691 ) -
ViewModelStoreOwneris now in Kotlin. This is a source incompatible change for classes written in Kotlin - they must now override theviewModelStoreproperty rather than implementing the previousgetViewModelStore()function. ( I86409 , b/240298691 ) - The Kotlin extension on
LifecycleOwnerthat provides thelifecycleScopefield has been moved to thelifecycle-commonartifact fromlifecycle-runtime-ktx. ( I41d78 , b/240298691 ) - The Kotlin extension on
Lifecyclethat provides thecoroutineScopefield has been moved to thelifecycle-commonartifact fromlifecycle-runtime-ktx. ( Iabb91 , b/240298691 )
Version 2.6.0-alpha05
25 января 2023 г.
androidx.lifecycle:lifecycle-*:2.6.0-alpha05 is released. Version 2.6.0-alpha05 contains these commits.
Kotlin Conversions
-
Transformationsis now written in Kotlin. This is a source incompatible change for those classes written in Kotlin that were directly using syntax such asTransformations.map- Kotlin code must now use the Kotlin extension method syntax that was previously only available when usinglifecycle-livedata-ktx. When using the Java programming language, the versions of these methods that take anandroidx.arch.core.util.Functionmethod are deprecated and replaced with the versions that take a KotlinFunction1. This change maintains binary compatibility. ( I8e14f ) -
ViewTreeViewModelStoreOwneris now written in Kotlin. This is a source incompatible change for those classes written in Kotlin - you must now directly import and use the Kotlin extension methods onViewofandroidx.lifecycle.setViewTreeViewModelStoreOwnerandandroidx.lifecycle.findViewTreeViewModelStoreOwnerto set and find a previously set owner. This is binary compatible and remains source compatible for implementations written in the Java programming language. ( Ia06d8 , Ib22d8 , b/240298691 ) - The
HasDefaultViewModelProviderFactoryinterface is now written in Kotlin. This is a source incompatible change for classes written in Kotlin - they must now override thedefaultViewModelProviderFactoryanddefaultViewModelCreationExtrasproperties rather than implementing the previous corresponding functions. ( Iaed9c , b/240298691 ) -
Observeris now written in Kotlin. ItsonChanged()method now uses the namevaluefor its parameter. ( Iffef2 , I4995e , b/240298691 ) -
AndroidViewModel,AbstractSavedStateViewModelFactory,LifecycleService,ServiceLifecycleDispatcher, andProcessLifecycleOwnerare now written in Kotlin ( I2e771 , Ibae40 , I160d7 , I08884 , I1cda7 , b/240298691 )
Version 2.6.0-alpha04
11 января 2023 г.
androidx.lifecycle:lifecycle-*:2.6.0-alpha04 is released. Version 2.6.0-alpha04 contains these commits.
Новые функции
-
LiveDatanow includes a newisInitializedproperty that indicates whether an explicit value has ever been set on theLiveData, allowing you to distinguish betweenliveData.valuereturningnullbecause no value has ever been set or an explicitnullvalue. ( Ibd018 )
Изменения API
- The
collectAsStateWithLifecycle()APIs oflifecycle-runtime-composeare no longer in experimental status. ( I09d42 , b/258835424 ) -
Lifecycle.launchWhenXmethods andLifecycle.whenXmethods have been deprecated as the use of a pausing dispatcher can lead to wasted resources in some cases. It is recommended to useLifecycle.repeatOnLifecycle. ( Iafc54 , b/248302832 )
Kotlin Conversions
-
ViewTreeLifecycleOwneris now written in Kotlin. This is a source incompatible change for those classes written in Kotlin - you must now directly import and use the Kotlin extension methods onViewofandroidx.lifecycle.setViewTreeLifecycleOwnerandandroidx.lifecycle.findViewTreeLifecycleOwnerto set and find a previously set owner. This replaces the previous Kotlin extension inlifecycle-runtime-ktx. This is binary compatible and remains source compatible for implementations written in the Java programming language. ( I8a77a , I5234e , b/240298691 ) -
LiveDataReactiveStreamsis now written in Kotlin. The Kotlin extensions previously inlifecycle-reactivestreams-ktxhave been moved into thelifecycle-reactivestreamsmodule and have become the primary surface for code written in Kotlin. This is a source incompatible change for code written in Kotlin if you were not already using the Kotlin extension method APIs. ( I2b1b9 , I95d22 , b/240298691 ) -
DefaultLifecycleObserver,LifecycleEventObserver,Lifecycle,LifecycleRegistry,LifecycleObserver, andViewModelStoreare now written in Kotlin ( Iadffd , ( I60034 , I8c52c , I9593d , I01fe1 , I59a23 , b/240298691 )
Исправления ошибок
-
SavedStateHandleno longer crashes with aClassCastExceptionwhen callingget()with the incorrect class type. ( I6ae7c )
Версия 2.6.0-альфа03
24 октября 2022 г.
androidx.lifecycle:lifecycle-*:2.6.0-alpha03 is released. Version 2.6.0-alpha03 contains these commits.
Исправления ошибок
- Fixed an issue with constraints between different Lifecycle modules not working as intended. ( I18d0d , b/249686765 )
- Errors thrown by
LifecycleRegistry.moveToState()now include a more helpful error messaging that informs developers of the component causing the error. ( Idf4b2 , b/244910446 )
Версия 2.6.0-альфа02
7 сентября 2022 г.
androidx.lifecycle:lifecycle-*:2.6.0-alpha02 is released. Version 2.6.0-alpha02 contains these commits.
Изменения API
-
MediatorLiveDatanow includes a constructor to set an initial value. ( Ib6cc5 , b/151244085 )
Исправления ошибок
-
Lifecycleartifacts now include constraints that ensure that all inter-dependent Lifecycle artifacts use the same version, automatically upgrading other dependencies when one is upgraded. b/242871265 -
FlowLiveData.asFlow()now creates acallbackFlowrather than using its ownChannelimplementation to ensure thread-safety and context preservation. ( I4a8b2 , b/200596935 ) -
FlowLiveData'sasLiveDatafunction will now preserve the initial value of aStateFlowwhen creating the newLiveDataobject. ( I3f530 , b/157380488 ) - From Lifecycle
2.5.1: Custom implementations ofAndroidViewModelFactorynow correctly calls thecreate(modelClass)function when using the stateful constructor withLifecycle2.4+ ( I5b315 , b/238011621 )
Версия 2.6.0-альфа01
29 июня 2022 г.
androidx.lifecycle:lifecycle-*:2.6.0-alpha01 is released. Version 2.6.0-alpha01 contains these commits.
Новые функции
- Added a new extension on
StateFlowandFlowofcollectAsStateWithLifecyclethat collect from flows and represents its latest value as Compose State in a lifecycle-aware manner. The flow is collected and the new emission is set to the State's value when the lifecycle is at least in a certainLifecycle.State. When the lifecycle falls below thatLifecycle.State, the flow collection stops and the State's value is not updated. ( I1856e , b/230557927 )
Версия 2.5
Версия 2.5.1
27 июля 2022 г.
androidx.lifecycle:lifecycle-*:2.5.1 is released. Version 2.5.1 contains these commits.
Исправления ошибок
- Custom implementations of
AndroidViewModelFactorynow correctly call thecreate(modelClass)function when using the statefulAndroidViewModelFactoryconstructor withLifecycle2.4+. ( I5b315 , b/238011621 )
Версия 2.5.0
29 июня 2022 г.
androidx.lifecycle:lifecycle-*:2.5.0 is released. Version 2.5.0 contains these commits.
Important changes since 2.4.0
SavedStateHandlenow offers agetStateFlow()API that returns a KotlinStateFlowfor monitoring value changes as an alternative to usingLiveData.ViewModel CreationExtras - when writing a custom
ViewModelProvider.Factory, it is no longer required to extendAndroidViewModelFactoryorAbstractSavedStateViewModelFactoryto gain access to anApplicationorSavedStateHandle, respectively. Instead, these fields are provided to everyViewModelProvider.Factorysubclass asCreationExtrasvia the new overload ofcreate:create(Class<T>, CreationExtras). These extras are provided automatically by your Activity or Fragment when using Activity1.5.0and Fragment1.5.0, respectively.class CustomFactory : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>, extras: CreationExtras): T { return when (modelClass) { HomeViewModel::class -> { // Get the Application object from extras val application = checkNotNull(extras[ViewModelProvider.AndroidViewModelFactory.APPLICATION_KEY]) // Pass it directly to HomeViewModel HomeViewModel(application) } DetailViewModel::class -> { // Create a SavedStateHandle for this ViewModel from extras val savedStateHandle = extras.createSavedStateHandle() DetailViewModel(savedStateHandle) } else -> throw IllegalArgumentException("Unknown class $modelClass") } as T } }lifecycle-viewmodelnow provides aviewModelFactoryKotlin DSL that allows you define yourViewModelProvider.Factoryin terms of one or more lambda initializers, one for each particularViewModelclass your custom factory supports, usingCreationExtrasas the primary data source.val customFactory = viewModelFactory { // The return type of the lambda automatically sets what class this lambda handles initializer { // Get the Application object from extras provided to the lambda val application = checkNotNull(get(ViewModelProvider.AndroidViewModelFactory.APPLICATION_KEY)) HomeViewModel(application) } initializer { val savedStateHandle = createSavedStateHandle() DetailViewModel(savedStateHandle) } }lifecycle-viewmodel-composenow offers aviewModel()API that takes a lambda factory for creating aViewModelinstance without requiring the creation of a customViewModelProvider.Factory.// Within a @Composable, you can now skip writing a custom Factory // and instead write a lambda to do the initialization of your ViewModel val detailViewModel = viewModel { // This lambda is only called the first time the ViewModel is created // and all CreationExtras are available inside the lambda val savedStateHandle = createSavedStateHandle() DetailViewModel(savedStateHandle) }SavedStateHandle Compose Saver Integration - the
lifecycle-viewmodel-composeartifact now contains new experimental APIs inSavedStateHandle.saveablethat allowrememberSaveablelike behavior backed by theSavedStateHandleof a `ViewModel.class ListScreenViewModel(handle: SavedStateHandle): ViewModel() { // This value survives both configuration changes and process death and recreation val editMode by handle.saveable { mutableStateOf(false) } }Added an
addCloseable()API and a new constructor overload that allow you to add one or moreCloseableobjects to theViewModelthat will be closed when theViewModelis cleared without requiring any manual work inonCleared().For instance, to create a coroutine scope that you can inject into a ViewModel, but control via testing, you can create a
CoroutineScopethat implementsCloseable:class CloseableCoroutineScope( context: CoroutineContext = SupervisorJob() + Dispatchers.Main.immediate ) : Closeable, CoroutineScope { override val coroutineContext: CoroutineContext = context override fun close() { coroutineContext.cancel() } }Which can then be used in your
ViewModelconstructor while maintaining the same lifetime asviewModelScope:class TestScopeViewModel( val customScope: CloseableCoroutineScope = CloseableCoroutineScope() ) : ViewModel(customScope) { // You can now use customScope in the same way as viewModelScope }
Изменения поведения
- Attempting to move the
Lifecycle.StatefromINITIALIZEDtoDESTROYEDwill now always throw anIllegalStateExceptionregardless of whether theLifecyclehas an attached observer. -
LifecycleRegistrywill now clear their observers when they reach theDESTROYEDstate.
Version 2.5.0-rc02
15 июня 2022 г.
androidx.lifecycle:lifecycle-*:2.5.0-rc02 is released. Version 2.5.0-rc02 contains these commits.
Исправления ошибок
-
ViewModelProviderwill no longer crash when mixing previous versions of compileOnly Lifecycle dependencies with versions 2.5+. ( I81a66 , b/230454566 )
Версия 2.5.0-rc01
11 мая 2022 г.
androidx.lifecycle:lifecycle-*:2.5.0-rc01 is released. Version 2.5.0-rc01 contains these commits.
Исправления ошибок
-
MediatorLiveData.addSource()now throws aNullPointerExceptionwhen passed anullsource instead of propagating thenullsource to observers.( Ibd0fb , b/123085232 )
Версия 2.5.0-beta01
20 апреля 2022 г.
androidx.lifecycle:lifecycle-*:2.5.0-beta01 is released. Version 2.5.0-beta01 contains these commits.
Изменения API
- Added
SavedStateHandle.saveableproperty delegates to use property names as keys for persisting state into theSavedStateHandle( I8bb86 , b/225014345 )
Исправления ошибок
- Fixed an issue where nesting one
NavHostwithin anotherNavHostin a non-primary bottom navigation tab would lead to anIllegalStateExceptionwhen using multiple back stacks. ( I11bd5 , b/228865698 )
Version 2.5.0-alpha06
6 апреля 2022 г.
androidx.lifecycle:lifecycle-*:2.5.0-alpha06 is released. Version 2.5.0-alpha06 contains these commits.
Новые функции
- Add experimental
MutableStateoverload toSavedStateHandle.saveablefor parity withrememberSaveable( I38cfe , b/224565154 )
Изменения API
-
CreationExtrasis now abstract instead of sealed. ( Ib8a7a )
Исправления ошибок
- Fixed an
IllegalStateException: Already attached to lifecycleOwnererror caused bySavedStateHandleController. ( I7ea47 , b/215406268 )
Version 2.5.0-alpha05
23 марта 2022 г.
androidx.lifecycle:lifecycle-*:2.5.0-alpha05 is released. Version 2.5.0-alpha05 contains these commits.
Новые функции
- The
lifecycle-viewmodel-composemodule now providesSavedStateHandleSaver, an experimental API that ensures values in aSavedStateHandleare integrated correctly with the same saved instance state thatrememberSaveableuses. ( Ia88b7 , b/195689777 )
Изменения API
- Fixed a compatibility issue with Lifecycle 2.3 and newer Lifecycle versions in Java. ( I52c8a , b/219545060 )
Исправления ошибок
-
SavedStateViewFactorynow supports usingCreationExtraseven when it was initialized with aSavedStateRegistryOwner. If extras are provided, the initialized arguments are ignored. ( I6c43b , b/224844583 )
Version 2.5.0-alpha04
9 марта 2022 г.
androidx.lifecycle:lifecycle-*:2.5.0-alpha04 is released. Version 2.5.0-alpha04 contains these commits.
Изменения API
-
SavedStateHandlenow offers agetStateFlow()API that returns a KotlinStateFlowfor monitoring value changes as an alternative to usingLiveData. ( Iad3ab , b/178037961 )
Версия 2.5.0-альфа03
23 февраля 2022 г.
androidx.lifecycle:lifecycle-*:2.5.0-alpha03 is released. Version 2.5.0-alpha03 contains these commits.
Новые функции
- Added an
addCloseable()API and a new constructor overload that allow you to add one or moreCloseableobjects to theViewModelthat will be closed when theViewModelis cleared without requiring any manual work inonCleared(). ( I55ea0 ) -
lifecycle-viewmodelnow provides anInitializerViewModelFactorythat allows you to add lambda for handling particularViewModelclasses, usingCreationExtrasas the primary data source. ( If58fc , b/216687549 ) -
lifecycle-viewmodel-composenow offers aviewModel()API that takes a lambda factory for creating aViewModelinstance without requiring the creation of a customViewModelProvider.Factory. ( I97fbb , b/216688927 )
Изменения API
- You can now create a
ViewModelwithCreationExtrasvialifecycle-viewmodel-compose. ( I08887 , b/216688927 )
Изменения поведения
- Attempting to move the
Lifecycle.StatefromINITIALIZEDtoDESTROYEDwill now always throw anIllegalStateExceptionregardless of whether theLifecyclehas an attached observer. ( I7c390 , b/177924329 ) -
LifecycleRegistrywill now clear their observers when they reach theDESTROYEDstate. ( I4f8dd , b/142925860 )
Версия 2.5.0-альфа02
9 февраля 2022 г.
androidx.lifecycle:lifecycle-*:2.5.0-alpha02 is released. Version 2.5.0-alpha02 contains these commits.
Изменения API
-
SavedStateHandleandSavedStateViewModelFactoryhave been converted to Kotlin. This has improved the nullability of the generics in both classes. ( Ib6ce2 , b/216168263 , I9647a , b/177667711 ) - The
LiveDataswitchMapfunction parameter can now have a nullable output. ( I40396 , b/132923666 ) - The
LiveData-ktx extensions are now annotated with@CheckResultto enforce that the result is used when calling these functions. ( Ia0f05 , b/207325134 )
Изменения поведения
-
SavedStateHandlenow properly stores the defaultValue when no value for the specified key exists. ( I1c6ce , b/178510877 )
Исправления ошибок
- From Lifecycle
2.4.1: Updatedlifecycle-processto depend on Startup 1.1.1 to ensure that fixes that preventProcessLifecycleInitializerfrom throwing aStartupExceptionare available by default. ( Ib01df , b/216490724 ) - There is now an improved error message when custom
AndroidViewModelclasses have parameters in the wrong order and attempt to create aViewModel. ( I340f7 , b/177667711 ) - You can now create a view model via
CreationExtrasusing theAndroidViewModelFactorywithout setting an application. ( I6ebef , b/217271656 )
Версия 2.5.0-альфа01
26 января 2022 г.
androidx.lifecycle:lifecycle-*:2.5.0-alpha01 is released. Version 2.5.0-alpha01 contains these commits.
ViewModel CreationExtras
With this release, we are laying the groundwork for restructuring how a ViewModel is constructed. Instead of a rigid set of subclasses of ViewModelProvider.Factory that each add additional functionality (allowing an Application constructor parameter via AndroidViewModelFactory , allowing a SavedStateHandle constructor parameter via SavedStateViewModelFactory and AbstractSavedStateViewModelFactory , etc.), we are moving to a world of stateless factories that rely on a new concept, CreationExtras . ( Ia7343 , b/188691010 , b/188541057 )
With this change, ViewModelProvider no longer makes direct calls into the previous create(Class<T>) method of ViewModelProvider.Factory . Instead, it calls into a new overload of create : create(Class<T>, CreationExtras) . This means that any direct implementation of the ViewModelProvider.Factory instance now has access to each of these new CreationExtras :
-
ViewModelProvider.NewInstanceFactory.VIEW_MODEL_KEY: thisStringprovides access to the custom key you passed toViewModelProvider.get(). -
ViewModelProvider.AndroidViewModelFactory.APPLICATION_KEYprovides access to theApplicationclass. -
SavedStateHandleSupport.SAVED_STATE_REGISTRY_OWNER_KEYprovides access to theSavedStateRegistryOwnerthat is being used to construct this ViewModel. -
SavedStateHandleSupport.VIEW_MODEL_STORE_OWNER_KEYprovides access to theViewModelStoreOwnerthat is being used to construct this ViewModel. -
SavedStateHandleSupport.DEFAULT_ARGS_KEYprovides access to theBundleof arguments that should be used to construct aSavedStateHandle.
These extras are provided by default when using Activity 1.5.0-alpha01 , Fragment 1.5.0-alpha01 , and Navigation 2.5.0-alpha01 . If you use an earlier version of those libraries, your CreationExtras will be empty - all of the existing subclasses of ViewModelProvider.Factory have been rewritten to support both the legacy creation path used by earlier versions of those libraries and the CreationExtras path which will be used going forward.
These CreationExtras allow you to construct a ViewModelProvider.Factory that passes just the information you need to each ViewModel without relying on a strict hierarchy of Factory subclasses:
class CustomFactory : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>, extras: CreationExtras): T {
return when (modelClass) {
HomeViewModel::class -> {
// Get the Application object from extras
val application = checkNotNull(extras[ViewModelProvider.AndroidViewModelFactory.APPLICATION_KEY])
// Pass it directly to HomeViewModel
HomeViewModel(application)
}
DetailViewModel::class -> {
// Create a SavedStateHandle for this ViewModel from extras
val savedStateHandle = extras.createSavedStateHandle()
DetailViewModel(savedStateHandle)
}
else -> throw IllegalArgumentException("Unknown class $modelClass")
} as T
}
}
We use the createSavedStateHandle() Kotlin extension function on CreationExtras from SavedStateHandleSupport to construct a SavedStateHandle only for the one ViewModel that needs it. ( Ia6654 , b/188541057 )
Custom CreationExtras can be provided by overriding getDefaultViewModelCreationExtras() in your ComponentActivity or Fragment , thus making them available to your custom ViewModelProvider.Factory as a built in form of assisted injection. These extras will automatically be made available to your custom Factory when used directly with ViewModelProvider or when using the by viewModels() and by activityViewModels() Kotlin property extensions. ( I79f2b , b/207012584 , b/207012585 , b/207012490 )
Исправления ошибок
- Fixed an issue where the default value provided to a
SavedStateHandlewould reappear after process death and recreation, even if it was specifically removed from theSavedStateHandle. As a consequence of this,SavedStateHandlewill no longer merge default values and restored values together, instead only using the restored values as the source of truth. ( I53a4b )
Версия 2.4
Версия 2.4.1
9 февраля 2022 г.
androidx.lifecycle:lifecycle-*:2.4.1 is released. Version 2.4.1 contains these commits.
Исправления ошибок
- Backported from Lifecycle
2.5.0-alpha01: Fixed an issue where the default value provided to aSavedStateHandlewould re-appear after process death and recreation, even if it was specifically removed from theSavedStateHandle. As a consequence of this,SavedStateHandlewill no longer merge default values and restored values together, instead only using the restored values as the source of truth. ( I53a4b ) -
lifecycle-processnow depends on Androidx Startup 1.1.1 which fixed a regression in where usingProcessLifecycleInitializerwould cause anStartupException. ( b/216490724 )
Версия 2.4.0
27 октября 2021 г.
androidx.lifecycle:lifecycle-*:2.4.0 is released. Version 2.4.0 contains these commits.
Важные изменения с версии 2.3.0
-
@OnLifecycleEventwas deprecated.LifecycleEventObserverorDefaultLifecycleObservershould be used instead. -
androidx.lifecycle:lifecycle-viewmodel-composelibrary was added. It providesviewModel()composable andLocalViewModelStoreOwner.- Source-breaking change :
ViewModelProviderhas been rewritten in Kotlin.ViewModelProvider.Factory.createmethod no longer allows nullable generic.
- Source-breaking change :
- New coroutines API were added to
androidx.lifecycle:lifecycle-runtime-ktx: -
Lifecycle.repeatOnLifecycle, API that executes a block of code in a coroutine when the Lifecycle is at least in a certain state. The block will cancel and re-launch as the lifecycle moves in and out of the target state; -
Flow.flowWithLifecycle, API that emits values from the upstream Flow when the lifecycle is at least in a certain state. -
DefaultLifecycleObserverwas moved fromlifecycle.lifecycle-common-java8tolifecycle.lifecycle-common.lifecycle.lifecycle-common-java8doesn't provide anymore any additional functionality on top oflifecycle.lifecycle-common, so dependency on it can be replaced bylifecycle.lifecycle-common. - Non coroutines API from
lifecycle-viewmodel-ktxhave been moved to thelifecycle-viewmodelmodule. lifecycle-processnow usesandroidx.startupto initialize theProcessLifecycleOwner.Previously, this was being done by
androidx.lifecycle.ProcessLifecycleOwnerInitializer.If you used
tools:node="remove"theContentProviderbeing used to initialize process lifecycle in the past, then you need to do the following instead.<provider android:name="androidx.startup.InitializationProvider" android:authorities=\"${applicationId}.androidx-startup" android:exported="false" tools:node=\"merge"> <!-- If you are using androidx.startup to initialize other components --> <meta-data android:name="androidx.lifecycle.ProcessLifecycleInitializer" android:value="androidx.startup" tools:node="remove" /> </provider>(или)
<!-- If you want to disable androidx.startup completely. --> <provider android:name="androidx.startup.InitializationProvider" android:authorities="${applicationId}.androidx-startup" tools:node="remove"> </provider>
Версия 2.4.0-rc01
29 сентября 2021 г.
androidx.lifecycle:lifecycle-*:2.4.0-rc01 is released with no changes from Lifecycle 2.4.0-beta01. Version 2.4.0-rc01 contains these commits.
Версия 2.4.0-beta01
15 сентября 2021 г.
androidx.lifecycle:lifecycle-*:2.4.0-beta01 is released. Version 2.4.0-beta01 contains these commits.
Изменения API
-
@OnLifecycleEventwas deprecated.LifecycleEventObserverorDefaultLifecycleObservershould be used instead. ( I5a8fa ) - DefaultLifecycleObserver was moved from
androidx.lifecycle.lifecycle-common-java8toandroidx.lifecycle.lifecycle-common.androidx.lifecycle.lifecycle-common-java8doesn't provide anymore any additional functionality on top ofandroidx.lifecycle.lifecycle-common, so dependency on it can be replaced byandroidx.lifecycle.lifecycle-common. ( I021aa ) - Non coroutines API from
lifecycle-viewmodel-ktxhave been moved to thelifecycle-viewmodelmodule. ( I6d5b2 )
Внешний вклад
Версия 2.4.0-альфа03
4 августа 2021 г.
androidx.lifecycle:lifecycle-*:2.4.0-alpha03 is released. Version 2.4.0-alpha03 contains these commits.
Изменения API
- Source-breaking change : ViewModelProvider has been rewritten in Kotlin.
ViewModelProvider.Factory.createmethod no longer allows nullable generic. ( I9b9f6 )
Изменения поведения
- The
Lifecycle.repeatOnLifecycle:blockis now always invoked serially when repeating execution. ( Ibab33 )
Внешний вклад
- Thanks chao2zhang for fixing the code snippets in the
repeatOnLifecycledocumentation. #205 .
Версия 2.4.0-альфа02
16 июня 2021 г.
androidx.lifecycle:lifecycle-*:2.4.0-alpha02 is released. Version 2.4.0-alpha02 contains these commits.
Новые функции
- Added a new
RepeatOnLifecycleWrongUsagelint check tolifecycle-runtime-ktxthat detects whenrepeateOnLifecycleis incorrectly used inonStart()oronResume(). ( 706078 , b/187887400 )
Изменения API
- The
LifecycleOwner.addRepeatingJobAPI is removed in favor ofLifecycle.repeatOnLifecyclethat respects structured concurrency and is easier to reason about. ( I4a3a8 ) - Make
ProcessLifecycleInitializerpublic so otherandroidx.startup.Initializers can use these as dependencies. ( I94c31 )
Исправления ошибок
- Fixed an issue with the
NullSafeMutableLiveDatalint check when the field has modifiers. ( #147 , b/183696616 ) - Fixed another issue with the
NullSafeMutableLiveDatalint check when using generics. ( #161 , b/184830263 )
Внешний вклад
- Thanks maxsav for improving the
NullSafeMutableLiveDatalint check. ( #147 , b/183696616 ) - Thanks kozaxinan for improving the
NullSafeMutableLiveDatalint check. ( #161 , b/184830263 )
Версия 2.4.0-альфа01
24 марта 2021 г.
androidx.lifecycle:lifecycle-*:2.4.0-alpha01 is released. Version 2.4.0-alpha01 contains these commits.
Изменения поведения
lifecycle-processnow usesandroidx.startupto initialize theProcessLifecycleOwner.Previously, this was being done by
androidx.lifecycle.ProcessLifecycleOwnerInitializer.If you used
tools:node="remove"theContentProviderbeing used to initialize process lifecycle in the past, then you need to do the following instead.<provider android:name="androidx.startup.InitializationProvider" android:authorities=\"${applicationId}.androidx-startup" android:exported="false" tools:node=\"merge"> <!-- If you are using androidx.startup to initialize other components --> <meta-data android:name="androidx.lifecycle.ProcessLifecycleInitializer" android:value="androidx.startup" tools:node="remove" /> </provider>(или)
<!-- If you want to disable androidx.startup completely. --> <provider android:name="androidx.startup.InitializationProvider" android:authorities="${applicationId}.androidx-startup" tools:node="remove"> </provider>
Изменения API
- Added a
Flow.flowWithLifecycleAPI that emits values from the upstream Flow when the lifecycle is at least in a certain state using theLifecycle.repeatOnLifecycleAPI. This is an alternative to the also newLifecycleOwner.addRepeatinJobAPI. ( I0f4cd )
Исправления ошибок
- From Lifecycle 2.3.1 : The
NonNullableMutableLiveDatalint rule can now properly differentiate between field variables with different nullability. ( b/169249668 )
Lifecycle Viewmodel Compose Version 1.0.0
Версия 1.0.0-альфа07
16 июня 2021 г.
androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha07 is released. Version 1.0.0-alpha07 contains these commits.
Критические изменения API
-
viewModel()now takes an optionalViewModelStoreOwner, making it easier to work with owners other than theLocalViewModelStoreOwner. For example, you can now useviewModel(navBackStackEntry)to retrieve a ViewModel associated with a particular navigation graph. ( I2628d , b/188693123 )
Версия 1.0.0-альфа06
2 июня 2021 г.
androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha06 is released. Version 1.0.0-alpha06 contains these commits.
Updated to be compatible with Compose version 1.0.0-beta08 .
Версия 1.0.0-альфа05
18 мая 2021 г.
androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha05 is released. Version 1.0.0-alpha05 contains these commits.
Новые функции
- Updated to be compatible with Compose version
1.0.0-beta07.
Исправления ошибок
- The AndroidManifest files from ui-test-manifest and ui-tooling-data are now compatible with Android 12 ( I6f9de , b/184718994 )
Версия 1.0.0-альфа04
7 апреля 2021 г.
androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha04 is released. Version 1.0.0-alpha04 contains these commits.
Изменения зависимости
- This version allows
androidx.hilt:hilt-navigation-composeandandroidx.navigation:navigation-composeto sync dependencies onandroidx.compose.compiler:compiler:1.0.0-beta04andandroidx.compose.runtime:runtime:1.0.0-beta04. For 1.0.0, it is required that the compiler and runtime match.
Версия 1.0.0-альфа03
10 марта 2021 г.
androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha03 is released. Version 1.0.0-alpha03 contains these commits.
Изменения API
-
LocalViewModelStoreOwner.currentnow returns a nullableViewModelStoreOwnerto better determine whether aViewModelStoreOwneris available in the current composition. APIs that require aViewModelStoreOwner, such asviewModel()andNavHost, still throw an exception if aViewModelStoreOwneris not set. ( Idf39a )
Lifecycle-Viewmodel-Compose Version 1.0.0-alpha02
24 февраля 2021 г.
androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha02 is released. Version 1.0.0-alpha02 contains these commits.
Изменения API
-
LocalViewModelStoreOwnernow has aprovidesfunctions that can be used withCompositionLocalProvider, replacing theasProvidableCompositionLocal()API. ( I45d24 )
Lifecycle-Viewmodel-Compose Version 1.0.0-alpha01
10 февраля 2021 г.
androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha01 is released. Version 1.0.0-alpha01 contains these commits.
Новые функции
- The
viewModel()composable andLocalViewModelStoreOwnerwere moved fromandroidx.compose.ui.viewinteropto this artifact in theandroidx.lifecycle.viewmodel.composepackage. ( I7a374 )
Версия 2.3.1
Lifecycle Version 2.3.1
24 марта 2021 г.
androidx.lifecycle:lifecycle-*:2.3.1 is released. Version 2.3.1 contains these commits.
Исправления ошибок
- The
NonNullableMutableLiveDatalint rule can now properly differentiate between field variables with different nullability. ( b/169249668 )
Версия 2.3.0
Версия 2.3.0
10 февраля 2021 г.
androidx.lifecycle:lifecycle-*:2.3.0 is released. Version 2.3.0 contains these commits.
Major changes since 2.2.0
-
SavedStateHandlesupport for non-parcelable classes :SavedStateHandlenow supports lazy serialization by allowing you to callsetSavedStateProvider()for a given key, providing aSavedStateProviderthat will get a callback tosaveState()when theSavedStateHandleis asked to save its state. See Saving non-parcelable classes . - Lifecycle Behavior Enforcement :
- LifecycleRegistry now enforces
DESTROYEDas a terminal state. -
LifecycleRegistrynow verifies that its methods are called on main thread. It was always a requirement for lifecycles of activities, fragments etc. An addition of observers from non-main threads resulted in hard to catch crashes in runtime. ForLifecycleRegistryobjects that owned by your own components, you can explicitly opt out from checks by usingLifecycleRegistry.createUnsafe(...), but then you have to ensure that a proper synchronization is in place when thisLifecycleRegistryis accessed from different threads.
- LifecycleRegistry now enforces
- Lifecycle State and Event Helpers : Added static helper methods of
downFrom(State),downTo(State),upFrom(State),upTo(State)toLifecycle.Eventfor generating theEventgiven aStateand transition direction. Added thegetTargetState()method that provides theStatethat the Lifecycle will transition to directly following theEvent. -
withStateAtLeast: AddedLifecycle.withStateAtLeastAPIs that await a lifecycle state and run a non-suspending block of code synchronously at the point of state change, then resume with the result. These APIs differ from the existingwhen*methods as they do not permit running suspending code and do not employ a custom dispatcher. ( aosp/1326081 ) -
ViewTreeAPIs : A newViewTreeLifecycleOwner.get(View)andViewTreeViewModelStoreOwner.get(View)API allows you to retrieve the containingLifecycleOwnerandViewModelStoreOwner, respectively, given aViewinstance. You must upgrade to Activity1.2.0and Fragment1.3.0, and AppCompat 1.3.0-alpha01 or higher to populate this correctly. ThefindViewTreeLifecycleOwnerandfindViewTreeViewModelStoreOwnerKotlin extensions are available inlifecycle-runtime-ktxandlifecycle-viewmodel-ktx, respectively. -
LiveData.observe()Kotlin extension deprecation : TheLiveData.observe()Kotlin extension necessary to use lambda syntax is now deprecated as it is not necessary when using Kotlin 1.4.
Версия 2.3.0-rc01
16 декабря 2020 г.
androidx.lifecycle:lifecycle-*:2.3.0-rc01 is released. Version 2.3.0-rc01 contains these commits.
Исправления ошибок
- The
keys()method ofSavedStateHandleis now consistent before and after the state is saved - it now includes keys previously used withsetSavedStateProvider()in addition to the keys used withset()andgetLiveData(). ( aosp/1517919 , b/174713653 )
Внешний вклад
- The APIs to suspend Lifecycle-aware coroutines now better handle calls to
yield(). Thanks Nicklas Ansman Giertz! ( aosp/1430830 , b/168777346 )
Версия 2.3.0-beta01
1 октября 2020 г.
androidx.lifecycle:lifecycle-*:2.3.0-beta01 is released. Version 2.3.0-beta01 contains these commits.
Изменения API
- The
LiveData.observe()Kotlin extension necessary to use lambda syntax is now deprecated as it is not necessary when using Kotlin 1.4. ( I40d3f )
Исправления ошибок
- Upgrade androidx to use Kotlin 1.4 ( Id6471 , b/165307851 , b/165300826 )
Изменения в документации
- The
liveDatabuilder andasLiveData()docs have been updated to include details about changing the given timeout values. ( aosp/1122324 )
Version 2.3.0-alpha07
19 августа 2020 г.
androidx.lifecycle:lifecycle-*:2.3.0-alpha07 is released. Version 2.3.0-alpha07 contains these commits.
Исправления ошибок
- Fixed a crash issue in the
NullSafeMutableLiveDataLint check. ( aosp/1395367 )
Version 2.3.0-alpha06
22 июля 2020 г.
androidx.lifecycle:lifecycle-*:2.3.0-alpha06 is released. Version 2.3.0-alpha06 contains these commits.
Новые функции
- Added static helper methods of
downFrom(State),downTo(State),upFrom(State),upTo(State)toLifecycle.Eventfor generating theEventgiven aStateand transition direction. Added thegetTargetState()method that provides theStatethat the Lifecycle will transition to directly following theEvent. ( I00887 ) - Added
Lifecycle.withStateAtLeastAPIs that await a lifecycle state and run a non-suspending block of code synchronously at the point of state change, then resume with the result. These APIs differ from the existingwhen*methods as they do not permit running suspending code and do not employ a custom dispatcher. ( aosp/1326081 )
Изменения поведения
- LifecycleRegistry now enforces
DESTROYEDas a terminal state. ( I00887 ) -
LifecycleRegistrynow verifies that its methods are called on main thread. It was always a requirement for lifecycles of activities, fragments etc. An addition of observers from non-main threads resulted in hard to catch crashes in runtime. ForLifecycleRegistryobjects that owned by your own components, you can explicitly opt out from checks by usingLifecycleRegistry.createUnsafe(...), but then you have to ensure that a proper synchronization is in place when thisLifecycleRegistryis accessed from different threads ( Ie7280 , b/137392809 )
Исправления ошибок
- Fixed a crash in
NullSafeMutableLiveData. ( b/159987480 ) - Fixed an
ObsoleteLintCustomCheckfor Lint checks bundled withlifecycle-livedata-core-ktx(and specificallyNullSafeMutableLiveData). ( b/158699265 )
Version 2.3.0-alpha05
24 июня 2020 г.
androidx.lifecycle:lifecycle-*:2.3.0-alpha05 is released. Version 2.3.0-alpha05 contains these commits.
Исправления ошибок
-
LiveDatanow better handles reentrant cases, avoiding duplicate calls toonActive()oronInactive(). ( b/157840298 ) - Fixed an issue where Lint checks would not run when using Android Studio 4.1 Canary 6 or higher. ( aosp/1331903 )
Версия 2.3.0-альфа04
10 июня 2020 г.
androidx.lifecycle:lifecycle-*:2.3.0-alpha04 is released. Version 2.3.0-alpha04 contains these commits.
Исправления ошибок
- Fixed a crash in the
NonNullableMutableLiveDataLint check. ( b/157294666 ) - The
NonNullableMutableLiveDataLint check now covers significantly more cases where anullvalue was set on aMutableLiveDatawith a non-null type parameter. ( b/156002218 )
Версия 2.3.0-альфа03
20 мая 2020 г.
androidx.lifecycle:lifecycle-*:2.3.0-alpha03 are released. Version 2.3.0-alpha03 contains these commits.
Новые функции
-
SavedStateHandlenow supports lazy serialization by allowing you to callsetSavedStateProvider()for a given key, providing aSavedStateProviderthat will get a callback tosaveState()when theSavedStateHandleis asked to save its state. ( b/155106862 ) - A new
ViewTreeViewModelStoreOwner.get(View)API allows you to retrieve the containingViewModelStoreOwnergiven aViewinstance. You must upgrade to Activity1.2.0-alpha05, Fragment1.3.0-alpha05, and AppCompat1.3.0-alpha01to populate this correctly. AfindViewModelStoreOwner()Kotlin extension has been added tolifecycle-viewmodel-ktx. ( aosp/1295522 )
Исправления ошибок
- Fixed an issue that caused the
MutableLiveDataLint checks released in Lifecycle2.3.0-alpha01from being published alongside thelifecycle-livedata-core-ktxartifact. ( b/155323109 )
Версия 2.3.0-альфа02
29 апреля 2020 г.
androidx.lifecycle:lifecycle-*:2.3.0-alpha02 is released. Version 2.3.0-alpha02 contains these commits.
Изменения API
-
SavedStateViewModelFactorynow allows you to pass a nullApplicationto its constructor to better support cases where one is not readily available and support forAndroidViewModelis not needed. ( aosp/1285740 )
Исправления ошибок
- Improved cold start performance by avoiding class verification failure on API 28 and lower devices. ( aosp/1282118 )
Версия 2.3.0-альфа01
4 марта 2020 г.
androidx.lifecycle:lifecycle-*:2.3.0-alpha01 is released. Version 2.3.0-alpha01 contains these commits.
Новые функции
- A new
ViewTreeLifecycleOwner.get(View)API allows you to retrieve the containingLifecycleOwnergiven aViewinstance. You must upgrade to Activity1.2.0-alpha01and Fragment1.3.0-alpha01to populate this correctly. AfindViewTreeLifecycleOwnerKotlin extension is available inlifecycle-runtime-ktx. ( aosp/1182361 , aosp/1182956 ) - Added a new Lint check that warns you when setting a
nullvalue on aMutableLiveDatathat has been defined in Kotlin as non-null. This is available when using thelivedata-core-ktxorlivedata-ktxartifacts. ( aosp/1154723 , aosp/1159092 ) - A new
lifecycle-runtime-testingartifact is available that provides aTestLifecycleOwnerthat implementsLifecycleOwnerand provides a thread safe mutableLifecycle. ( aosp/1242438 )
Исправления ошибок
- The
lifecycle-runtimeartifact now has a unique package name. ( aosp/1187196 )
Версия 2.2.0
ViewModel-Savedstate Version 2.2.0
5 февраля 2020 г.
androidx.lifecycle:lifecycle-viewmodel-savedstate:2.2.0 is released. Version 2.2.0 contains these commits .
Lifecycle ViewModel SavedState now shares the same version as other Lifecycle artifacts. The behavior of 2.2.0 is identical to the behavior of 1.0.0 .
Версия 2.2.0
22 января 2020 г.
androidx.lifecycle:lifecycle-*:2.2.0 is released. Version 2.2.0 contains these commits .
Важные изменения с версии 2.1.0
- Lifecycle Coroutine Integration : The new
lifecycle-runtime-ktxartifact adds integration between Lifecycle and Kotlin coroutines. Thelifecycle-livedata-ktxhas also been expanded to take advantage of coroutines. See Use Kotlin coroutines with Architecture Components for more details. -
ViewModelProviders.of()deprecation :ViewModelProviders.of()has been deprecated. You can pass aFragmentorFragmentActivityto the newViewModelProvider(ViewModelStoreOwner)constructor to achieve the same functionality when using Fragment1.2.0. -
lifecycle-extensionsArtifact Deprecation : With the above deprecation ofViewModelProviders.of(), this release marks the deprecation of the last API inlifecycle-extensionsand this artifact should now be considered deprecated in its entirety. We strongly recommend depending on the specific Lifecycle artifacts you need (such aslifecycle-serviceif you're usingLifecycleServiceandlifecycle-processif you're usingProcessLifecycleOwner) rather thanlifecycle-extensionsas there will not be a future2.3.0release oflifecycle-extensions. - Gradle Incremental Annotation Processor : Lifecycle's annotation processor is incremental by default. If your app is written in the Java 8 programming language you can use
DefautLifecycleObserverinstead; and if it's written in the Java 7 programming language you can useLifecycleEventObserver.
Version 2.2.0-rc03
4 декабря 2019 г.
androidx.lifecycle:lifecycle-*:2.2.0-rc03 is released. Version 2.2.0-rc03 contains these commits .
Исправления ошибок
- Fixed a failure occurring when a mocked
ViewModelwas stored inViewModelStoreand queried later with default factory. - Fix a usage of
Dispatchers.Main.immediateinlaunchWhenCreatedand similar methods to be called synchronously during corresponding lifecycle event. ( aosp/1156203 )
Внешние взносы
- Thanks to Anders Järleberg for contributing the fix! ( aosp/1156203 )
- Thanks to Vsevolod Tolstopyatov from Jetbrains for reviewing an implementation of inlined execution.
Dependency changes
- Lifecycle Extensions now depends on Fragment
1.2.0-rc03.
Version 2.2.0-rc02
7 ноября 2019 г.
androidx.lifecycle:lifecycle-*:2.2.0-rc02 is released. Version 2.2.0-rc02 contains these commits .
Исправления ошибок
- Fixed a bug in the proguard setup of the library that affected devices running API 28+ if the target API is below 29. ( b/142778206 )
Версия 2.2.0-rc01
23 октября 2019 г.
androidx.lifecycle:lifecycle-*:2.2.0-rc01 is released. Version 2.2.0-rc01 contains these commits .
Исправления ошибок
- Fixed an issue where
launchWhenCreatedand related methods would run one frame later than the associated lifecycle method due to its use ofDispatchers.Maininstead ofDispatchers.Main.immediate. ( aosp/1145596 )
Внешние взносы
- Thanks to Nicklas Ansman for contributing the fix! ( aosp/1145596 )
Версия 2.2.0-beta01
9 октября 2019 г.
androidx.lifecycle:lifecycle-*:2.2.0-beta01 is released. Version 2.2.0-beta01 contains these commits .
Исправления ошибок
- Fixed a regression introduced in Lifecycle 2.2.0-alpha05 in the ordering of
ProcessLifecycleOwnerand the activity'sLifecycleOwnermoving to started and resumed on Android 10 devices. ( aosp/1128132 ) - Fixed a regression introduced in Lifecycle
2.2.0-alpha05which would cause aNullPointerExceptionwhen using version2.0.0or2.1.0oflifecycle-process. ( b/141536990 )
Версия 2.2.0-альфа05
18 сентября 2019 г.
androidx.lifecycle:lifecycle-*:2.2.0-alpha05 is released. Version 2.2.0-alpha05 contains these commits .
Исправления ошибок
- Fixed a race condition in coroutine livedata builder. b/140249349
Version 2.2.0-alpha04
5 сентября 2019 г.
androidx.lifecycle:lifecycle-*:2.2.0-alpha04 is released. The commits included in this version can be found here .
Новые функции
-
lifecycleScope,whenCreated,whenStarted,whenResumed,viewModelScope, and the underlying implementation ofliveDatanow useDispatchers.Main.immediateinstead ofDispatchers.Main. ( b/139740492 )
Внешние взносы
- Thanks to Nicklas Ansman for contributing the move to
Dispatchers.Main.immediate! ( aosp/1106073 )
Version 2.2.0-alpha03
7 августа 2019 г.
androidx.lifecycle:lifecycle-*:2.2.0-alpha03 is released. The commits included in this version can be found here .
Новые функции
- Implementations of
ViewModelStoreOwnercan now optionally implementHasDefaultViewModelProviderFactoryto provide a defaultViewModelProvider.Factory. This has been done for Activity1.1.0-alpha02, Fragment1.2.0-alpha02, and Navigation2.2.0-alpha01. ( aosp/1092370 , b/135716331 )
Изменения API
-
ViewModelProviders.of()has been deprecated. You can pass aFragmentorFragmentActivityto the newViewModelProvider(ViewModelStoreOwner)constructor to achieve the same functionality. ( aosp/1009889 )
Версия 2.2.0-альфа02
2 июля 2019 г.
androidx.lifecycle:*:2.2.0-alpha02 is released. The commits included in this version can be found here .
Изменения API
- Replaced
LiveDataScope.initialValuewithLiveDataScope.latestValuewhich will track the current emitted value of theliveDatablock. - Added a new overload to the
liveDatabuilder that receivestimeoutparameter as typeDuration
Версия 2.2.0-альфа01
7 мая 2019 г.
androidx.lifecycle:*:2.2.0-alpha01 is released. The commits included in this version can be found here .
Новые функции
- This release adds new features that adds support for Kotlin coroutines for Lifecycle and LiveData. Detailed documentation on them can be found here .
ViewModel-SavedState Version 1.0.0
Версия 1.0.0
22 января 2020 г.
androidx.lifecycle:lifecycle-viewmodel-savedstate:1.0.0 is released. Version 1.0.0 contains these commits .
Important features in 1.0.0
- New SavedStateHandle class was added. It enables your
ViewModelclasses to access and to contribute to the saved state. This object can be received in constructor ofViewModelclass and factories provided by default by Fragments and AppCompatActivity will injectSavedStateHandleautomatically. - AbstractSavedStateViewModelFactory was added. It allows you to create custom factories for your
ViewModeland provide them access toSavedStateHandle.
ViewModel-Savedstate Version 1.0.0-rc03
4 декабря 2019 г.
androidx.lifecycle:lifecycle-viewmodel-savedstate:1.0.0-rc03 is released. Version 1.0.0-rc03 contains these commits .
Dependency changes
- Lifecycle ViewModel SavedState now depends on Lifecycle
2.2.0-rc03.
Viewmodel-Savedstate Version 1.0.0-rc02
7 ноября 2019 г.
androidx.lifecycle:lifecycle-viewmodel-savedstate:1.0.0-rc02 is released. Version 1.0.0-rc02 contains these commits .
Dependency changes
- Now depends on lifecycle
2.2.0-rc02.
ViewModel-SavedState Version 1.0.0-rc01
23 октября 2019 г.
androidx.lifecycle:lifecycle-viewmodel-savedstate:1.0.0-rc01 is released with no changes from 1.0.0-beta01 . Version 1.0.0-rc01 contains these commits .
ViewModel-Savedstate Version 1.0.0-beta01
9 октября 2019 г.
androidx.lifecycle:lifecycle-viewmodel-savedstate:1.0.0-beta01 is released. Version 1.0.0-beta01 contains these commits .
Исправления ошибок
- Fixed an issue where accessing a SavedState ViewModel for the first time in
Activity.onActivityResult()would result in anIllegalStateException. ( b/139093676 ) - Fixed an
IllegalStateExceptionwhen usingAbstractSavedStateViewModelFactory. ( b/141225984 )
ViewModel-SavedState Version 1.0.0-alpha05
18 сентября 2019 г.
androidx.lifecycle:lifecycle-viewmodel-savedstate:1.0.0-alpha05 is released. Version 1.0.0-alpha05 contains these commits .
Изменения API
-
SavedStateViewModelFactoryno longer extendsAbstractSavedStateViewModelFactoryandSavedStateHandleis created only for ViewModels that requested have it ( aosp/1113593 )
ViewModel-SavedState Version 1.0.0-alpha03
7 августа 2019 г.
androidx.lifecycle:lifecycle-viewmodel-savedstate:1.0.0-alpha03 is released. The commits included in this version can be found here .
Критические изменения
-
lifecycle-viewmodel-savedstateno longer depends onfragmentand the relatedSavedStateViewModelFactory(Fragment)andSavedStateViewModelFactory(FragmentActivity)constructors have been removed. Instead,SavedStateViewModelFactoryis now the default factory for Activity1.1.0-alpha02, Fragment1.2.0-alpha02, and Navigation2.2.0-alpha01. ( b/135716331 )
ViewModel-SavedState Version 1.0.0-alpha02
2 июля 2019 г.
androidx.lifecycle:lifecycle-viewmodel-savedstate:1.0.0-alpha02 is released. The commits included in this version can be found here .
Новые функции
- Added
SavedStateHandle.getLiveData()overload which accepts a default value.
Изменения API
-
SavedStateVMFactoryis renamed toSavedStateViewModelFactory. -
AbstractSavedStateVMFactoryis renamed toAbstractSavedStateViewModelFactory.
ViewModel-Savedstate Version 1.0.0-alpha01
13 марта 2019 г.
androidx.lifecycle:lifecycle-viewmodel-savedstate:1.0.0-alpha01 is released. The full commit log for this initial release can be found here .
Новые функции
- Now
ViewModelscan contribute to savedstate. To do that you use newly introduced viewmodel's factorySavedStateVMFactoryand your ViewModel should have a constructor that receivesSavedStateHandleobject as a parameter.
Версия 2.1.0
Important changes since 2.0.0
- Added
LifecycleEventObserverfor the cases when a stream of lifecycle events is needed. It is a public API instead of a hiddenGenericLifecycleObserverclass. - Added ktx extensions for
LiveData.observemethods andTransformations.*methods. - Added
Transformations.distinctUntilChanged, which creates a new LiveData object that does not emit a value until the sourceLiveDatavalue has been changed. - Added coroutine support in ViewModels by adding the extension property
ViewModel.viewModelScope.
Версия 2.1.0
5 сентября 2019 г.
androidx.lifecycle:lifecycle-*:2.1.0 is released. The commits included in this version can be found here .
Версия 2.1.0-rc01
2 июля 2019 г.
androidx.lifecycle:*:2.1.0-rc01 is released with no changes from androidx.lifecycle:*:2.1.0-beta01 . The commits included in this version can be found here .
Версия 2.1.0-beta01
7 мая 2019 г.
androidx.lifecycle:*:2.1.0-beta01 is released. The commits included in this version can be found here .
Новые функции
- Lifecycles are graduated to beta: api introduced in previous alphas such as
liveDataextension functions for transformations and observations,ViewModelinitialisation with property delegation and others are stabilised and not going to change.
Версия 2.1.0-альфа04
3 апреля 2019 г.
androidx.lifecycle:*:2.1.0-alpha04 is released. The commits included in this version can be found here .
Изменения API
- Breaking change: the underlying API behind
by viewModels()andby activityViewModels()has been changed to support aViewModelStoredirectly, rather than only aViewModelStoreOwner. ( aosp/932932 )
Версия 2.1.0-альфа03
13 марта 2019 г.
androidx.lifecycle:*:2.1.0-alpha03 is released. The full list of commits included in this version can be found here .
Изменения API
-
ViewModelProvider.KeyedFactorywas removed. Second interface in addition toViewModelProvider.Factorydidn't compose well with new features as property delegation in Kotlinby viewmodels {}. ( aosp/914133 )
Версия 2.1.0-альфа02
30 января 2019 г.
androidx.lifecycle 2.1.0-alpha02 is released.
Изменения API
-
LifecycleRegistrynow contains asetCurrentState()method that replaces the now deprecatedsetState()method. ( aosp/880715 )
Исправления ошибок
- Fixed an issue where mock
ViewModelinstances would crash when the containingViewModelStorewas cleared. b/122273087
Версия 2.1.0-альфа01
17 декабря 2018 г.
androidx.lifecycle 2.1.0-alpha01 is released.
Новые функции
- Added
LifecycleEventObserverfor the cases when a stream of lifecycle events is needed. It is a public api instead of a hiddenGenericLifecycleObserverclass. - Added ktx extensions for
LiveData.observemethods andTransformations.*methods. - Method
Transformations.distinctUntilChangedwas added. It creates a newLiveDataobject that does not emit a value until the source LiveData value has been changed. - Coroutine support in ViewModels: extension property
ViewModel.viewModelScopewas added. - Added
ViewModelProvider.KeyedFactory, a factory for ViewModels that receiveskeyandClassincreatemethod.
Версия 2.0.0
Версия 2.0.0
21 сентября 2018 г.
Lifecycle 2.0.0 is released with one bugfix from 2.0.0-rc01 in ViewModel.
Исправления ошибок
- Fixed a ViewModel proguard rule that incorrectly removed constructors b/112230489
Версия 2.0.0-beta01
2 июля 2018 г.
Исправления ошибок
- Fixed LifecycleObserver proguard rule to keep only implementations, not subinterfaces b/71389427
- Fixed ViewModel proguard rules to allow obfuscation and shrinking
Pre-AndroidX Versions
For the pre-AndroidX versions of Lifecycle that follow, include these dependencies:
dependencies {
def lifecycle_version = "1.1.1"
// ViewModel and LiveData
implementation "android.arch.lifecycle:extensions:$lifecycle_version"
// alternatively - just ViewModel
implementation "android.arch.lifecycle:viewmodel:$lifecycle_version" // For Kotlin use viewmodel-ktx
// alternatively - just LiveData
implementation "android.arch.lifecycle:livedata:$lifecycle_version"
// alternatively - Lifecycles only (no ViewModel or LiveData).
// Support library depends on this lightweight import
implementation "android.arch.lifecycle:runtime:$lifecycle_version"
annotationProcessor "android.arch.lifecycle:compiler:$lifecycle_version" // For Kotlin use kapt instead of annotationProcessor
// alternately - if using Java8, use the following instead of compiler
implementation "android.arch.lifecycle:common-java8:$lifecycle_version"
// optional - ReactiveStreams support for LiveData
implementation "android.arch.lifecycle:reactivestreams:$lifecycle_version"
// optional - Test helpers for LiveData
testImplementation "android.arch.core:core-testing:$lifecycle_version"
}
Версия 1.1.1
21 марта 2018 г.
Only one small change: android.arch.core.util.Function is moved from arch:runtime to arch:common . This allows it to be used without the runtime dependency, eg in paging:common below.
lifecycle:common is a dependency of lifecycle:runtime , so this change doesn't affect lifecycle:runtime directly, only modules that depend directly on lifecycle:common , as Paging does.
Версия 1.1.0
22 января 2018 г.
Изменения в упаковке
New, much smaller dependencies are now available:
-
android.arch.lifecycle:livedata:1.1.0 -
android.arch.lifecycle:viewmodel:1.1.0
Изменения API
- The deprecated
LifecycleActivityandLifecycleFragmenthave now been removed - please useFragmentActivity,AppCompatActivityor supportFragment. -
@NonNullannotations have been added toViewModelProvidersandViewModelStores -
ViewModelProvidersconstructor has been deprecated - please use its static methods directly -
ViewModelProviders.DefaultFactoryhas been deprecated - please useViewModelProvider.AndroidViewModelFactory - The static
ViewModelProvider.AndroidViewModelFactory.getInstance(Application)method has been added to retrieve a staticFactorysuitable for creatingViewModelandAndroidViewModelinstances.