Жизненный цикл
В этой таблице перечислены все артефакты группы androidx.lifecycle
.
Артефакт | Стабильный выпуск | Кандидат на выпуск | Бета-версия | Альфа-релиз |
---|---|---|---|---|
жизненный цикл-* | 2.8.6 | - | - | 2.9.0-альфа03 |
жизненный цикл-представление-модель-составление | 2.8.6 | - | - | 2.9.0-альфа03 |
Объявление зависимостей
Чтобы добавить зависимость от Lifecycle, вам необходимо добавить в свой проект репозиторий Google Maven. Для получения дополнительной информации прочтите репозиторий Google Maven .
Добавьте зависимости для нужных вам артефактов в файл build.gradle
для вашего приложения или модуля:
Котлин
классный
dependencies { def lifecycle_version = "2.8.7" 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" // 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.8.7" 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") // 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.8.7" 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.8.7" 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.9
Версия 2.9.0-альфа03
18 сентября 2024 г.
Выпущен androidx.lifecycle:lifecycle-*:2.9.0-alpha03
. Версия 2.9.0-alpha03 содержит эти коммиты .
Исправления ошибок
- Из жизненного цикла
2.8.6
: ошибкаNullSafeMutableLiveData
Lint улучшила поддержку интеллектуального приведения, что позволяет избежать ложных срабатываний. ( 85фед6 , б/181042665 )
Обновления зависимостей
- Из жизненного цикла
2.8.6
: Compose среды выполнения жизненного цикла теперь зависит от Compose Runtime1.7.1
- Время выполнения жизненного цикла теперь зависит от ProfileInstaller
1.4.0
Версия 2.9.0-альфа02
4 сентября 2024 г.
Выпущен androidx.lifecycle:lifecycle-*:2.9.0-alpha02
. Версия 2.9.0-alpha02 содержит эти коммиты .
Исправления ошибок
- Начиная с жизненного цикла
2.8.5
: обновите правила ProGuardandroidx.lifecycle.ReportFragment
, чтобы разрешить обфускацию. ( ff898e1 )
Внешний вклад
- Переместите
androidx.compose.ui.platform.LocalLifecycleOwner
в общий исходный набор (KMP). Спасибо Ивану Маткову из JetBrains за вклад. ( 8cd5d03 ) - Начиная с жизненного цикла
2.8.5
: делегат расширения SavedStateHandle.saveable теперь поддерживает значения, допускающие значение NULL. Спасибо Роману Калукевичу за вклад. ( 0d78ea6 )
Версия 2.9.0-альфа01
7 августа 2024 г.
Выпущен androidx.lifecycle:lifecycle-*:2.9.0-alpha01
. Версия 2.9.0-alpha01 содержит эти коммиты .
Котлин Мультиплатформа
-
lifecycle-testing
теперь совместимо с KMP. ( Iea41e ) - Добавлена поддержка многоплатформенной цели Kotlin
linuxArm64
( I139d3 , b/338268719 ).
Новые возможности
- Доступен новый артефакт KMP
androidx.lifecycle:lifecycle-viewmodel-testing
, который предоставляет классViewModelScenario
для изолированного тестирования ViewModels с поддержкойonCleared
(все платформы) иSavedStateHandle
(только Android). ( 337f68d , c9b3409 , 9799a95c , b/264602919 ) - Создание
ViewModel
с помощьюViewModelProvider
теперь является потокобезопасным; Аннотации@MainThread
были удалены. ( Ifd978 , б/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.6
18 сентября 2024 г.
Выпущен androidx.lifecycle:lifecycle-*:2.8.6
. Версия 2.8.6 содержит эти коммиты .
Исправления ошибок
- Ошибка
NullSafeMutableLiveData
Lint улучшила поддержку интеллектуального приведения, что позволяет избежать ложных срабатываний. ( 85фед6 , б/181042665 )
Обновления зависимостей
- Жизненный цикл выполнения Compose теперь зависит от Compose Runtime
1.7.1
Версия 2.8.5
4 сентября 2024 г.
Выпущен androidx.lifecycle:lifecycle-*:2.8.5
. Версия 2.8.5 содержит эти коммиты .
Исправления ошибок
- Обновите правила
androidx.lifecycle.ReportFragment
ProGuard, чтобы разрешить обфускацию. ( ff898e1 )
Внешний вклад
- Делегат расширения
SavedStateHandle.saveable
теперь поддерживает значения, допускающие значение NULL. Спасибо Роману Калукевичу за вклад. ( 0d78ea6 )
Версия 2.8.4
24 июля 2024 г.
Выпущен androidx.lifecycle:lifecycle-*:2.8.4
. Версия 2.8.4 содержит эти коммиты .
Исправления ошибок
-
LiveData.asFlow()
теперь правильно обрабатывает случаи, когда возвращаемый Flow немедленно завершается после получения значения, уже установленного вLiveData
(например, при использованииtake(1)
). ( I9c566 ) - Завершение
Lifecycle*Effect
теперь идемпотентно (т. е., еслиonStopOrDispose
был вызван из-за остановки жизненного цикла, он не будет вызываться второй раз после удаления, если жизненный цикл снова не вернется кSTARTED
). ( I5f607 , б/352364595 )
Версия 2.8.3
1 июля 2024 г.
Выпущен androidx.lifecycle:lifecycle-*:2.8.3
. Версия 2.8.3 содержит эти коммиты .
Исправления ошибок
- Исправлена проблема с обратной совместимостью Lifecycle 2.8 с Compose 1.6.0 и более ранними версиями при использовании сжатия кода. ( аосп/3133056 , б/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 без каких-либо обходных путей. ( аосп/3105647 , б/336842920 ) -
ViewModelProvider
больше не будет аварийно завершать работу при смешивании предыдущих версий зависимостей жизненного циклаcompileOnly
с версиями 2.8+, что устраняет проблемы с такими библиотеками, как LeakCanary. ( I80383 , б/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
для совместимости. ( аосп/3079334 , б/339562627 ) -
saveable
интеграцияViewModel
с использованием делегатов свойств теперь использует имя класса как часть автоматически создаваемого ключа, что позволяет избежать конфликтов, если несколько классов используют один и тот жеSavedStateHandle
. ( аосп/3063463 )
Версия 2.8.0
14 мая 2024 г.
Выпущен androidx.lifecycle:lifecycle-*:2.8.0
. Версия 2.8.0 содержит эти коммиты .
Важные изменения с версии 2.7.0
-
LocalLifecycleOwner
был перенесен из пользовательского интерфейса Compose вlifecycle-runtime-compose
, чтобы его вспомогательные API на основе Compose можно было использовать за пределами пользовательского интерфейса Compose. - Артефакт
lifecycle-runtime-compose
теперь содержит APIdropUnlessResumed
иdropUnlessStarted
, которые позволяют отбрасывать клики или другие события, которые происходят даже после того, какLifecycleOwner
опустился ниже заданногоLifecycle.State
. Например, это можно использовать с Navigation Compose, чтобы избежать обработки событий щелчка после того, как переход на другой экран уже начался:onClick: () -> Unit = dropUnlessResumed { navController.navigate(NEW_SCREEN) }
ViewModel.viewModelScope
теперь является переопределяемым параметром конструктора, позволяющим вам внедрить собственный диспетчер иSupervisorJob()
или переопределить значение по умолчанию, используяbackgroundScope
доступный вrunTest
. ( I2817c , б / 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 сохранена, но есть несколько заметных изменений при сравнении поверхности Android API с общей поверхностью API:
- Создание экземпляра
ViewModelProvider
теперь выполняется с помощью методовViewModelProvider.create()
а не непосредственного вызова его конструктора. -
ViewModelProvider.NewInstanceFactory
иViewModelProvider.AndroidViewModelFactory
доступны только на Android.- Пользовательские фабрики рекомендуется расширять из
ViewModelProvider.Factory
и использовать методcreate
, который принимаетCreationExtras
, или использоватьviewModelFactory
Kotlin 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
не был должным образом упакован. Теперь они упакованы в AARlifecycle-runtime
. ( аосп/3038274 , б/322382422 ) - Исправлено непреднамеренное изменение порядка очистки экземпляров
AutoCloseable
, прикрепленных к ViewModel: был восстановлен предыдущий порядокaddCloseable(String, AutoCloseable)
, затемaddClosable(AutoCloseable)
иonCleared()
. ( аосп/3041632 ) - Улучшите поведение создания по умолчанию для
viewModelScope
для собственных сред и сред рабочего стола JVM. ( аосп/3039221 )
Внешний вклад
- Спасибо Виктору Кроппу за улучшение проверки основного потока на JVM Desktop. ( аосп/3037116 )
Версия 2.8.0-бета01
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
. ( б/330323282 )
Исправления ошибок
-
NullSafeMutableLiveData
был переработан, чтобы избежать множества ложных срабатываний. ( I2d8c1 , Iafb18 , I03463 , I7ecef )
Обновление зависимостей
- Артефакт
lifecycle-viewmodel-compose
теперь зависит от Compose 1.6.0. - Жизненный цикл теперь зависит от установщика профиля 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 , б / 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. ( б/214568825 )
Чтобы учесть это изменение, такие методы, как методы ViewModelProvider
, которые принимали java.lang.Class<T>
теперь имеют эквивалентный метод, который принимает kotlin.reflect.KClass<T>
.
Бинарная совместимость на Android сохранена, но есть несколько заметных изменений при сравнении поверхности Android API с общей поверхностью API:
- Создание экземпляра
ViewModelProvider
теперь выполняется с помощью методовViewModelProvider.create()
а не непосредственного вызова его конструктора. -
ViewModelProvider.NewInstanceFactory
иViewModelProvider.AndroidViewModelFactory
доступны только на Android.- Пользовательские фабрики рекомендуется расширять из
ViewModelProvider.Factory
и использовать методcreate
, который принимаетCreationExtras
, или использоватьviewModelFactory
Kotlin DSL.
- Пользовательские фабрики рекомендуется расширять из
- Использование
ViewModelProvider
без специальной фабрики на платформах, отличных от JVM, приведет к исключениюUnsupportedOperationException
. На платформах JVM совместимость сохраняется за счет использования конструктора ViewModel без аргументов, если пользовательская фабрика не указана. -
viewModelScope
вернется кEmptyCoroutineContext
на платформах, гдеDispatchers.Main
недоступен (например, Linux).
Изменения поведения
-
InitializerViewModelFactory
(включая функцию построенияviewModelFactory
) теперь будет выдавать исключениеIllegalArgumentException
, еслиinitializer
с тем жеclazz: KClass<VM : ViewModel>
уже добавлен. ( Ic3a36 )
Исправления ошибок
-
ViewModel.getCloseable
теперь обрабатывает дублированные ключи: если сkey
уже связан ресурсAutoCloseable
, старый ресурс будет заменен и немедленно закрыт. ( Ибеб67 ) - Доступ к
viewModelScope
ViewModel
теперь является потокобезопасным. ( Если4766 , б/322407038 )
Внешний вклад
-
LocalLifecycleOwner
перешёл из пользовательского интерфейса Compose в пользовательский интерфейс жизненного цикла, чтобы его вспомогательные API на основе Compose можно было использовать за пределами пользовательского интерфейса Compose. Спасибо Джейку Уортону за вклад. ( I6c41b , б/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 )
Котлин-преобразования
-
ViewModel
теперь написана на Kotlin ( I16f26 , b/214568825 ). - Расширения kotlin
lifecycle-viewmodel-ktx
теперь перенесены в базовый модуль жизненного цикла. ( Id787b , b/274800183 ) - Расширения kotlin
lifecycle-runtime-ktx
теперь перенесены в базовый модуль жизненного цикла. ( Ic3686 , б/274800183 ) - Расширения kotlin
lifecycle-livedata-core-ktx
теперь перенесены в базовый модуль жизненного цикла. ( I54a3d , б/274800183 )
Мультиплатформенная совместимость Kotlin
- Основные API жизненного цикла в
Lifecycle
,LifecycleOwner
,LifecycleObserver
,Lifecycle.State
,Lifecycle.Event
иLifecycleRegistry
теперь поставляются в виде артефактов, совместимых с Kotlin Multiplatform. ( б/317249252 )
Изменения API
- Вызов
LifecycleStartEffect
иLifecycleResumeEffect
без ключа теперь является ошибкой в соответствии с тем же соглашением, что и APIDisposableEffect
, который отражают эти API. ( Ib0e0c , б/323518079 ) -
ViewModel
теперь используетAutoCloseable
вместоCloseable
. Это обратно совместимое изменение. ( I27f8e , б / 214568825 ) -
LiveDataReactiveStreams.toPublisher(lifecycleOwner, liveData)
устарел в пользуLiveData.toPublisher(lifecycleOwner)
. ( Ябе29 , б/262623005 )
Внешний вклад
- Спасибо Ивану Маткову из Jetbrains за помощь в переносе Lifecycle на мультиплатформу Kotlin. ( 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
— если дляLiveData
установленоvalue
, функцияmap
/switchMap
будет немедленно вызвана для заполненияvalue
возвращаемогоLiveData
. Это гарантирует, что начальное значение будет установлено как часть первой композиции (при использовании сobserveAsState()
), но не меняет поведение наблюдения — значения обновлений из источникаLiveData
по-прежнему будут применяться только после того, как вы начнете наблюдать заLiveData
. - В этом выпуске исправлена проблема, из-за которой
SavedStateHandle
не мог должным образом восстанавливать пользовательские классыParcelable
после смерти и воссоздания процесса. Из-за того, что информация о типе теряется платформой Android, массивы пользовательских Parcelables требуют дополнительной работы (создание типизированного массива нужного типа вручную), и документация поget
,getLiveData
иgetStateFlow
теперь специально устраняет это ограничение. - Правила хранения proguard, связанные с
LifecycleObserver
были удалены. Это означает, что защищенный код, который хочет использовать API-интерфейсы посредством отражения (например, используя давно устаревшую аннотацию@OnLifecycleEvent
), должен будет предоставить свои собственные правила хранения для своего конкретного варианта использования.
Наблюдение за событиями жизненного цикла
- В качестве альтернативы использованию
LifecycleEventObserver
теперь вы можете наблюдатьFlow
Lifecycle.Event
с помощью метода расширенияLifecycle.asFlow()
. - Пользователи Jetpack Compose теперь могут использовать
LifecycleEventEffect
для запуска побочных эффектов Compose на основеLifecycle.Event
.
@Composable
fun HomeScreen(viewModel: HomeViewModel = viewModel()) {
LifecycleEventEffect(Lifecycle.Event.ON_RESUME) {
viewModel.refreshData()
}
// …
}
- Пользователи Jetpack Compose могут использовать
LifecycleStartEffect
иLifecycleResumeEffect
для обработки пар событий — начало, остановка и возобновление, пауза соответственно. Этот API отражает API, найденный вDisposableEffect
, и подходит для случаев, когда изменение, вносимое при повышении состояния, необходимо отменить при понижении.
fun HomeScreen(viewModel: HomeViewModel = viewModel()) {
LifecycleStartEffect(viewModel) {
val timeTracking = viewModel.startTrackingTimeOnScreen()
onStopOrDispose {
timeTracking.stopTrackingTimeOnScreen()
}
}
// …
}
Дополнительные сведения см. в разделе Запуск кода при событиях жизненного цикла .
Наблюдаемость за состоянием жизненного цикла
- Текущий
Lifecycle.State
теперь можно наблюдать через свойствоLifecycle.currentStateFlow
, которое возвращаетStateFlow
, гдеvalue
является текущийLifecycle.State
. - Пользователи Jetpack Compose могут использовать расширение
Lifecycle.currentStateAsState()
чтобы напрямую предоставлятьLifecycle.State
как ComposeState
. Это эквивалент (и более короткая альтернатива)lifecycle.currentStateFlow.collectAsState()
.
Дополнительные сведения см. в разделе Сбор состояния жизненного цикла с помощью потоков .
Версия 2.7.0-rc02
13 декабря 2023 г.
Выпущен androidx.lifecycle:lifecycle-*:2.7.0-rc02
. Версия 2.7.0-rc02 содержит эти коммиты.
Исправления ошибок
- Исправлена проблема, из-за которой
SavedStateHandle
не восстанавливал должным образом пользовательские классыParcelable
после смерти и воссоздания процесса. Из-за того, что информация о типе теряется платформой Android, массивы пользовательских Parcelables требуют дополнительной работы (создание типизированного массива нужного типа вручную), и документация поget
,getLiveData
иgetStateFlow
теперь специально устраняет это ограничение. ( I0b55a )
Версия 2.7.0-rc01
15 ноября 2023 г.
Выпущен androidx.lifecycle:lifecycle-*:2.7.0-rc01
. Версия 2.7.0-rc01 содержит эти коммиты.
Исправления ошибок
-
LifecycleStartEffect
иLifecycleResumeEffect
теперь правильно удаляют и воссоздают блок эффекта, еслиLifecycleOwner
изменен. ( Ia25c6 )
Версия 2.7.0-бета01
1 ноября 2023 г.
androidx.lifecycle:lifecycle-*:2.7.0-beta01
выпущен без изменений. Версия 2.7.0-beta01 содержит эти коммиты.
- Обновление бета-версии, никаких серьезных изменений в этой версии нет.
Версия 2.7.0-альфа03
18 октября 2023 г.
Выпущен androidx.lifecycle:lifecycle-*:2.7.0-alpha03
. Версия 2.7.0-alpha03 содержит эти коммиты.
Новые возможности
-
lifecycle-runtime-testing
теперь содержит новую проверку Lint, позволяющую избежать установкиLifecycle.State
TestLifecycleOwner
с использованием поляcurrentState
внутри сопрограммы. Проверка Lint теперь предлагает приостановитьsetCurrentState
, что позволяет установитьLifecycle.State
без блокировки. ( Icf728 , б/297880630 )
Исправления ошибок
- Исправлена проблема с
LiveData.switchMap
, из-за которой возврат одного и того же экземпляраLiveData
как при первоначальном вызове, так и при последующем вызове препятствовал добавлению экземпляраLiveData
в качестве источника. ( Ibedcba7 )
Версия 2.7.0-альфа02
6 сентября 2023 г.
Выпущен androidx.lifecycle:lifecycle-*:2.7.0-alpha02
. Версия 2.7.0-alpha02 содержит эти коммиты.
Новые возможности
-
TestLifecycleOwner
теперь включает в себя функцию приостановкиsetCurrentState()
чтобы дать пользователям возможность использоватьTestLifecycleOwner
из сопрограммы, например, предоставленнойrunTest
. ( I329de , б / 259344129 )
Изменения API
- Все файлы из модулей
lifecycle-livedata-ktx
были перемещены в основной модульlifecycle-livedata
. ( I10c6f , б / 274800183 )
Изменения поведения
- Расширения
LiveData.map()
иLiveData.switchMap()
теперь устанавливаютvalue
возвращаемогоLiveData
, если для предыдущегоLiveData
было установлено значение, гарантируя, что использование результирующего LiveData в Jetpack Compose имеет правильное состояние в исходной композиции. . ( I91d2b , б/269479952 ) - Функция
addCloseable()
ViewModel
теперь немедленно закрываетCloseable
, еслиViewModel
уже получила вызовonCleared()
. ( I4712e , б / 280294730 )
Исправления ошибок
- Из жизненного цикла
2.6.2
: исправлена проблема, из-за которойSavedStateHandle
не мог быть правильно восстановлен после смерти процесса, если состояние было восстановлено,save()
вызывался без фактического сохранения состояния в родительскомSavedStateRegistry
, а затем состояние восстанавливалось снова. Это исправляет взаимодействие междуrememberSaveable
иNavHost
Navigation Compose. ( аосп/2729289 )
Версия 2.7.0-альфа01
26 июля 2023 г.
Выпущен androidx.lifecycle:lifecycle-*:2.7.0-alpha01
. Версия 2.7.0-alpha01 содержит эти коммиты.
Изменения API
-
Lifecycle.State
теперь доступен для наблюдения Compose черезLifecycle.currentStateFlow
, который возвращаетStateFlow
, гдеvalue
является текущийLifecycle.State
. ( Ib212d , б/209684871 ) -
Lifecycle.Event
теперь можно наблюдать какFlow
с помощьюLifecycle.asFlow().
( If2c0f , b/176311030 ) - Был добавлен API
LifecycleResumeEffect
для запуска ComposeSideEffect
на основе обратных вызовов событийLifecycle.Event.ON_RESUME
иLifecycle.Event.ON_PAUSE
. ( I60386 , б / 235529345 ) - Был добавлен API
LifecycleStartEffect
для запуска ComposeSideEffect
на основе обратных вызовов событийLifecycle.Event.ON_START
иLifecycle.Event.ON_STOP
. ( I5a8d1 , б/235529345 ) - Был добавлен API
LifecycleEventEffect
для запуска ComposeSideEffect
на основеLifecycle.Event
. ( Ic9794 , б/235529345 ) - Было добавлено расширение
Lifecycle.collectAsState()
позволяющее напрямую предоставлятьLifecycle.State
как ComposeState
. Это эквивалент (и более короткая альтернатива)lifecycle.currentStateFlow.collectAsState()
. ( I11015 , б / 235529345 )
Исправления ошибок
- Расширение
LiveData.distinctUntilChanged()
теперь устанавливаетvalue
возвращаемогоLiveData
, если для предыдущегоLiveData
было установлено значение. Это не меняет поведение наблюдения — обновленные значения из исходногоLiveData
по-прежнему будут применяться только после того, как вы начнете наблюдать заLiveData
, возвращаемым изdistinctUntilChanged()
. ( Ib482f ) - Правила хранения proguard, связанные с
LifecycleObserver
были удалены. Это означает, что защищенный код, желающий использовать API посредством отражения, должен будет предоставить свои собственные правила хранения для конкретного варианта использования. ( Ia12fd )
Версия 2.6
Версия 2.6.2
6 сентября 2023 г.
Выпущен androidx.lifecycle:lifecycle-*:2.6.2
. Версия 2.6.2 содержит эти коммиты.
Исправления ошибок
- Исправлена проблема, из-за которой
SavedStateHandle
не восстанавливался правильно после смерти процесса, если состояние было восстановлено,save()
вызывался без фактического сохранения состояния в родительскомSavedStateRegistry
, а затем состояние восстанавливалось снова. Это исправляет взаимодействие междуrememberSaveable
иNavHost
из Navigation Compose. ( аосп/2729289 )
Версия 2.6.1
22 марта 2023 г.
Выпущен androidx.lifecycle:lifecycle-*:2.6.1
. Версия 2.6.1 содержит эти коммиты.
Обновления зависимостей
-
lifecycle-viewmodel-savedstate
теперь зависит от SavedState1.2.1
. ( cd7251 ) - Жизненный цикл теперь зависит от ProfileInstaller
1.3.0
. ( f9d30b )
Версия 2.6.0
8 марта 2023 г.
Выпущен androidx.lifecycle:lifecycle-*:2.6.0
. Версия 2.6.0 содержит эти коммиты.
Важные изменения с версии 2.5.0
-
LiveData
теперь включает новое свойствоisInitialized
, которое указывает, было ли когда-либо установлено явное значение дляLiveData
, что позволяет вам различатьliveData.value
, возвращающийnull
поскольку значение никогда не было установлено, или явноеnull
значение. -
MediatorLiveData
теперь включает конструктор для установки начального значения. - Добавлено новое расширение для
StateFlow
иFlow
методаcollectAsStateWithLifecycle()
которое собирает данные из потоков и представляет их последнее значение как Compose State с учетом жизненного цикла. - Методы
Lifecycle.launchWhenX
иLifecycle.whenX
признаны устаревшими, поскольку использование диспетчера приостановки в некоторых случаях может привести к пустой трате ресурсов. Рекомендуется использоватьLifecycle.repeatOnLifecycle
. Для получения дополнительной информации о однократной приостановке работы см. объяснение того , почему это по своей сути небезопасно. - Преобразование Kotlin . Большое количество классов жизненного цикла было преобразовано в Kotlin. Все преобразованные классы по-прежнему сохраняют двоичную совместимость с предыдущими версиями. Следующие классы имеют несовместимые с исходным кодом изменения для классов, написанных на Kotlin:
ViewTreeLifecycleOwner
,LiveDataReactiveStreams
,HasDefaultViewModelProviderFactory
,ViewTreeViewModelStoreOwner
,Transformations
,ViewModelStoreOwner
,LifecycleOwner
В таблице ниже представлены преобразования исходного кода для новой версии жизненного цикла.
Жизненный цикл 2.5 | Жизненный цикл 2.5 (KTX) | Жизненный цикл 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 |
- Обнуляемость метода
onChanged
Observer
, созданного в Kotlin, теперь соответствует обнуляемости универсального типа. Если вы хотите, чтобыObserver.onChanged()
принимал тип, допускающий значение NULL, вы должны создать экземплярObserver
с типом, допускающим значение NULL. - Эти классы также были преобразованы в Kotlin, но остались совместимыми с исходным кодом:
DefaultLifecycleObserver
,LifecycleEventObserver
,Lifecycle
,LifecycleRegistry
,LifecycleObserver
,ViewModelStore
,AndroidViewModel
,AbstractSavedStateViewModelFactory
,LifecycleService
,ServiceLifecycleDispatcher
иProcessLifecycleOwner
.
Версия 2.6.0-rc01
22 февраля 2023 г.
Выпущен androidx.lifecycle:lifecycle-*:2.6.0-rc01
. Версия 2.6.0-rc01 содержит эти коммиты.
Исправления ошибок
- Расширение
LiveData.distinctUntilChanged()
теперь устанавливаетvalue
возвращаемогоLiveData
, если для предыдущегоLiveData
было установлено значение. Это не меняет поведение наблюдения — обновленные значения из исходногоLiveData
по-прежнему будут применяться только после того, как вы начнете наблюдать заLiveData
, возвращаемым изdistinctUntilChanged()
. ( Ib482f )
Версия 2.6.0-бета01
8 февраля 2023 г.
Выпущен androidx.lifecycle:lifecycle-*:2.6.0-beta01
. Версия 2.6.0-beta01 содержит эти коммиты.
Котлин-преобразования
-
LifecycleOwner
теперь написан на Kotlin. Это изменение, несовместимое с исходным кодом, для классов, написанных на Kotlin — теперь они должны переопределять свойствоlifecycle
, а не реализовывать предыдущую функциюgetLifecycle()
. ( I75b4b , б/240298691 ) -
ViewModelStoreOwner
теперь находится в Kotlin. Это изменение, несовместимое с исходным кодом, для классов, написанных на Kotlin — теперь они должны переопределить свойствоviewModelStore
, а не реализовывать предыдущую функциюgetViewModelStore()
. ( I86409 , б / 240298691 ) - Расширение Kotlin для
LifecycleOwner
, предоставляющее полеlifecycleScope
было перенесено вlifecycle-common
артефакт изlifecycle-runtime-ktx
. ( I41d78 , б/240298691 ) - Расширение Kotlin для
Lifecycle
, предоставляющее полеcoroutineScope
было перенесено вlifecycle-common
артефакт изlifecycle-runtime-ktx
. ( Ябб91 , б/240298691 )
Версия 2.6.0-альфа05
25 января 2023 г.
Выпущен androidx.lifecycle:lifecycle-*:2.6.0-alpha05
. Версия 2.6.0-alpha05 содержит эти коммиты.
Котлин-преобразования
-
Transformations
теперь написаны на Котлине. Это изменение, несовместимое с исходным кодом для тех классов, написанных на Kotlin, которые напрямую использовали синтаксис, такой какTransformations.map
— код Kotlin теперь должен использовать синтаксис метода расширения Kotlin, который ранее был доступен только при использованииlifecycle-livedata-ktx
. При использовании языка программирования Java версии этих методов, принимающие методandroidx.arch.core.util.Function
считаются устаревшими и заменяются версиями, принимающими KotlinFunction1
. Это изменение поддерживает двоичную совместимость. ( I8e14f ) -
ViewTreeViewModelStoreOwner
теперь написан на Kotlin. Это изменение, несовместимое с исходным кодом для классов, написанных на Kotlin — теперь вы должны напрямую импортировать и использовать методы расширения Kotlin вView
androidx.lifecycle.setViewTreeViewModelStoreOwner
иandroidx.lifecycle.findViewTreeViewModelStoreOwner
чтобы установить и найти ранее установленного владельца. Он совместим на двоичном уровне и остается совместимым с исходным кодом для реализаций, написанных на языке программирования Java. ( Ia06d8 , Ib22d8 , b/240298691 ) - Интерфейс
HasDefaultViewModelProviderFactory
теперь написан на Kotlin. Это изменение, несовместимое с исходным кодом, для классов, написанных на Kotlin — теперь они должны переопределять свойстваdefaultViewModelProviderFactory
иdefaultViewModelCreationExtras
а не реализовывать предыдущие соответствующие функции. ( Iaed9c , б/240298691 ) -
Observer
теперь написан на Kotlin. Его методonChanged()
теперь используетvalue
имени для своего параметра. ( Iffef2 , I4995e , b/240298691 ) -
AndroidViewModel
,AbstractSavedStateViewModelFactory
,LifecycleService
,ServiceLifecycleDispatcher
иProcessLifecycleOwner
теперь написаны на Kotlin ( I2e771 , Ibae40 , I160d7 , I08884 , I1cda7 , b/240298691 ).
Версия 2.6.0-альфа04
11 января 2023 г.
Выпущен androidx.lifecycle:lifecycle-*:2.6.0-alpha04
. Версия 2.6.0-alpha04 содержит эти коммиты.
Новые возможности
-
LiveData
теперь включает новое свойствоisInitialized
, которое указывает, было ли когда-либо установлено явное значение дляLiveData
, что позволяет вам различатьliveData.value
, возвращающийnull
поскольку значение никогда не было установлено, или явноеnull
значение. ( Там же018 )
Изменения API
- API-интерфейсы
collectAsStateWithLifecycle()
дляlifecycle-runtime-compose
больше не находятся в экспериментальном состоянии. ( I09d42 , б / 258835424 ) - Методы
Lifecycle.launchWhenX
иLifecycle.whenX
устарели, так как использование диспетчера приостановки в некоторых случаях может привести к потере ресурсов. Рекомендуется использоватьLifecycle.repeatOnLifecycle
. ( Iafc54 , б/248302832 )
Котлин-преобразования
-
ViewTreeLifecycleOwner
теперь написан на Kotlin. Это несовместимое изменение источника для тех классов, написанных в Kotlin - теперь вы должны непосредственно импортировать и использовать методы расширения Kotlin вView
androidx.lifecycle.setViewTreeLifecycleOwner
иandroidx.lifecycle.findViewTreeLifecycleOwner
для установки и поиска ранее набор владельца. Это заменяет предыдущее расширение Kotlin вlifecycle-runtime-ktx
. Это бинарно совместим и остается источником, совместимым с реализациями, написанными на языке программирования Java. ( I8a77a , i5234e , b/240298691 ) -
LiveDataReactiveStreams
теперь написан в Котлине. Ранее расширения Kotlin вlifecycle-reactivestreams-ktx
были перемещены в модульlifecycle-reactivestreams
и стали основной поверхностью для кода, написанного в котлине. Это несовместимое изменение источника для кода, написанного в Котлине, если вы еще не использовали API метода расширения Kotlin. ( I2b1b9 , i95d22 , b/240298691 ) -
DefaultLifecycleObserver
,LifecycleEventObserver
,Lifecycle
,LifecycleRegistry
,LifecycleObserver
иViewModelStore
теперь написаны в Kotlin ( IADFFD , ( I60034 , I8C52C , I9593D , I01FE1 , I59A23, B/2402989898989111), I01FE1, I59A23 , B/24029898989891.8691 ).
Исправления ошибок
-
SavedStateHandle
больше не сбивается сClassCastException
при вызовеget()
с неправильным типом класса. ( I6ae7c )
Версия 2.6.0-Alpha03
24 октября 2022 г.
androidx.lifecycle:lifecycle-*:2.6.0-alpha03
. Версия 2.6.0-Alpha03 содержит эти коммиты.
Исправления ошибок
- Исправлена проблема с ограничениями между различными модулями жизненного цикла, которые не работают, как предполагалось. ( I18D0D , B/249686765 )
- Ошибки, брошенные
LifecycleRegistry.moveToState()
теперь включают более полезные обмене сообщениями об ошибках, которая информирует разработчиков компонента, вызывающего ошибку. ( IDF4B2 , B/244910446 )
Версия 2.6.0-Alpha02
7 сентября 2022 г.
androidx.lifecycle:lifecycle-*:2.6.0-alpha02
выпускается. Версия 2.6.0-Alpha02 содержит эти коммиты.
Изменения API
-
MediatorLiveData
теперь включает в себя конструктор для установки начального значения. ( IB6CC5 , B/151244085 )
Исправления ошибок
- Артефакты
Lifecycle
теперь включают ограничения , которые гарантируют, что все межзависимые артефакты жизненного цикла используют одну и ту же версию, автоматически обновляя другие зависимости при обновлении. B/242871265 -
FlowLiveData.asFlow()
теперь создаетcallbackFlow
а не использует свою собственную реализациюChannel
для обеспечения безопасности потока и сохранения контекста. ( I4a8b2 , b/200596935 ) - Функция
asLiveData
FlowLiveData
теперь сохранит начальное значениеStateFlow
при создании нового объектаLiveData
. ( I3f530 , b/157380488 ) - Из жизненного цикла
2.5.1
: пользовательские реализацииAndroidViewModelFactory
теперь правильно вызывает функциюcreate(modelClass)
при использовании конструктора StateRul сLifecycle
2.4+ ( I5B315 , B/238011621 )
Версия 2.6.0-Alpha01
29 июня 2022 г.
androidx.lifecycle:lifecycle-*:2.6.0-alpha01
выпускается. Версия 2.6.0-Alpha01 содержит эти коммиты.
Новые возможности
- Добавлено новое расширение на
StateFlow
иFlow
collectAsStateWithLifecycle
, которые собираются из потоков и представляют его последнее значение в качестве состояния составления в целом в жизненном цикле. Поток собирается, и новая эмиссия устанавливается на значение состояния, когда жизненный цикл, по крайней мере, в определенномLifecycle.State
. Когда жизненный цикл падает ниже тогоLifecycle.State
. ( I1856E , B/230557927 )
Версия 2.5
Версия 2.5.1
27 июля 2022 г.
androidx.lifecycle:lifecycle-*:2.5.1
выпускается. Версия 2.5.1 содержит эти коммиты.
Исправления ошибок
- Пользовательские реализации
AndroidViewModelFactory
теперь правильно вызовут функциюcreate(modelClass)
при использовании конструктораAndroidViewModelFactory
сLifecycle
2.4+. ( I5b315 , b/238011621 )
Версия 2.5.0
29 июня 2022 г.
androidx.lifecycle:lifecycle-*:2.5.0
выпускается. Версия 2.5.0 содержит эти коммиты.
Важные изменения с 2.4.0
SavedStateHandle
теперь предлагает APIgetStateFlow()
, который возвращает KotlinStateFlow
для мониторинга изменений стоимости в качестве альтернативы использованиюLiveData
.ViewModel CreationExtras - При написании пользовательского
ViewModelProvider.Factory
больше не требуется расширятьAndroidViewModelFactory
илиAbstractSavedStateViewModelFactory
, чтобы получить доступ кApplication
илиSavedStateHandle
, соответственно. Вместо этого эти поля предоставляются для каждого подклассаViewModelProvider.Factory
какCreationExtras
через новую перегрузкуcreate
:create(Class<T>, CreationExtras)
. Эти дополнения предоставляются автоматически вашей деятельностью или фрагментом при использовании активности1.5.0
и фрагмента1.5.0
соответственно.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-viewmodel
теперь предоставляетviewModelFactory
Kotlin DSL, который позволяет вам определить свойViewModelProvider.Factory
с точки зрения одного или нескольких инициализаторов Lambda, один для каждого конкретного классаViewModel
, которые ваши пользовательские заводские опоры с использованиемCreationExtras
в качестве основного источника данных.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-compose
теперь предлагает APIviewModel()
, который занимает фабрику Lambda для создания экземпляраViewModel
не требуя создания пользовательскогоViewModelProvider.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 -Артефакт
lifecycle-viewmodel-compose
теперь содержит новые экспериментальные API вSavedStateHandle.saveable
, который позволяетrememberSaveable
как поведение, поддерживаемоеSavedStateHandle
of `ViewModel.class ListScreenViewModel(handle: SavedStateHandle): ViewModel() { // This value survives both configuration changes and process death and recreation val editMode by handle.saveable { mutableStateOf(false) } }
Добавлено API
addCloseable()
и новая перегрузка конструктора, которая позволяет вам добавлять один или несколькоCloseable
объектов вViewModel
, которые будут закрыты, когдаViewModel
очищена, не требуя никакой ручной работы вonCleared()
.Например, чтобы создать прицел из -за корзины, который вы можете ввести в ViewModel, но управляйте через тестирование, вы можете создать
CoroutineScope
, который реализуетCloseable
:class CloseableCoroutineScope( context: CoroutineContext = SupervisorJob() + Dispatchers.Main.immediate ) : Closeable, CoroutineScope { override val coroutineContext: CoroutineContext = context override fun close() { coroutineContext.cancel() } }
Который затем может быть использован в вашем конструкторе
ViewModel
сохраняя при этом ту же срок службы, что иviewModelScope
:class TestScopeViewModel( val customScope: CloseableCoroutineScope = CloseableCoroutineScope() ) : ViewModel(customScope) { // You can now use customScope in the same way as viewModelScope }
Поведение изменяется
- Попытка переместить
Lifecycle.State
Государство отINITIALIZED
вDESTROYED
теперь всегда бросаетIllegalStateException
независимо от того, имеет лиLifecycle
прикрепленный наблюдатель. -
LifecycleRegistry
теперь очистит своих наблюдателей, когда они достигнутDESTROYED
состояния.
Версия 2.5.0-RC02
15 июня 2022 года
androidx.lifecycle:lifecycle-*:2.5.0-rc02
выпускается. Версия 2.5.0-RC02 содержит эти коммиты.
Исправления ошибок
-
ViewModelProvider
больше не будет сбои при смешивании предыдущих версий зависимостей для жизненного цикла компонента с версиями 2.5+. ( I81a66 , b/230454566 )
Версия 2.5.0-RC01
11 мая 2022 г.
androidx.lifecycle:lifecycle-*:2.5.0-rc01
выпускается. Версия 2.5.0-RC01 содержит эти коммиты.
Исправления ошибок
-
MediatorLiveData.addSource()
теперь бросаетNullPointerException
при передачеnull
источника вместо распространенияnull
источника наблюдателям. ( IBD0FB , B/123085232 )
Версия 2.5.0-бета01
20 апреля 2022 года
androidx.lifecycle:lifecycle-*:2.5.0-beta01
выпускается. Версия 2.5.0-бета01 содержит эти коммиты.
Изменения API
- Добавлены делегаты
SavedStateHandle.saveable
Property для использования имен свойств в качестве ключей для постоянного состояния вSavedStateHandle
( I8BB86 , B/225014345 )
Исправления ошибок
- Исправлена проблема, в которой гнездовывание одного
NavHost
в другомNavHost
на неприимкой вкладке нижней навигации приведет кIllegalStateException
при использовании нескольких стеков задних. ( I11bd5 , b/228865698 )
Версия 2.5.0-Alpha06
6 апреля 2022 г.
androidx.lifecycle:lifecycle-*:2.5.0-alpha06
выпускается. Версия 2.5.0-Alpha06 содержит эти коммиты.
Новые возможности
- Добавьте экспериментальную перегрузку
MutableState
вSavedStateHandle.saveable
для паритета сrememberSaveable
( i38cfe , B/224565154 )
Изменения API
-
CreationExtras
теперь абстрактно, а не герметично. ( IB8A7A )
Исправления ошибок
- Исправлена
IllegalStateException: Already attached to lifecycleOwner
вызваннойSavedStateHandleController
. ( I7ea47 , b/215406268 )
Версия 2.5.0-Alpha05
23 марта 2022 г.
androidx.lifecycle:lifecycle-*:2.5.0-alpha05
выпускается. Версия 2.5.0-Alpha05 содержит эти коммиты.
Новые возможности
- Модуль
lifecycle-viewmodel-compose
теперь предоставляетSavedStateHandleSaver
, экспериментальный API, который обеспечивает значения вSavedStateHandle
правильно интегрированы с тем же сохраненным состоянием экземпляра, котороеrememberSaveable
применение. ( IA88B7 , B/195689777 )
Изменения API
- Исправлена проблема совместимости с жизненным циклом 2.3 и более новыми версиями жизненного цикла в Java. ( I52c8a , b/219545060 )
Исправления ошибок
-
SavedStateViewFactory
теперь поддерживает использованиеCreationExtras
, даже если он был инициализирован с помощьюSavedStateRegistryOwner
. Если предоставляются дополнения, инициализированные аргументы игнорируются. ( I6c43b , b/224844583 )
Версия 2.5.0-Alpha04
9 марта 2022 г.
androidx.lifecycle:lifecycle-*:2.5.0-alpha04
. Версия 2.5.0-Alpha04 содержит эти коммиты.
Изменения API
-
SavedStateHandle
теперь предлагает APIgetStateFlow()
, который возвращает KotlinStateFlow
для мониторинга изменений стоимости в качестве альтернативы использованиюLiveData
. ( IAD3AB , B/178037961 )
Версия 2.5.0-Alpha03
23 февраля 2022 г.
androidx.lifecycle:lifecycle-*:2.5.0-alpha03
выпускается. Версия 2.5.0-Alpha03 содержит эти коммиты.
Новые возможности
- Добавлено API
addCloseable()
и новая перегрузка конструктора, которая позволяет вам добавлять один или несколькоCloseable
объектов вViewModel
, которые будут закрыты, когдаViewModel
очищена, не требуя никакой ручной работы вonCleared()
. ( I55ea0 ) -
lifecycle-viewmodel
теперь предоставляетInitializerViewModelFactory
, которая позволяет добавлять лямбду для обработки определенных классовViewModel
, используяCreationExtras
в качестве основного источника данных. ( If58fc , b/216687549 ) -
lifecycle-viewmodel-compose
теперь предлагает APIviewModel()
, который занимает фабрику Lambda для создания экземпляраViewModel
не требуя создания пользовательскогоViewModelProvider.Factory
. ( I97FBB , B/216688927 )
Изменения API
- Теперь вы можете создать
ViewModel
сCreationExtras
черезlifecycle-viewmodel-compose
. ( I08887 , B/216688927 )
Поведение изменяется
- Попытка переместить
Lifecycle.State
Государство отINITIALIZED
вDESTROYED
теперь всегда бросаетIllegalStateException
независимо от того, имеет лиLifecycle
прикрепленный наблюдатель. ( I7C390 , B/177924329 ) -
LifecycleRegistry
теперь очистит своих наблюдателей, когда они достигнутDESTROYED
состояния. ( I4f8dd , b/142925860 )
Версия 2.5.0-Alpha02
9 февраля 2022 г.
androidx.lifecycle:lifecycle-*:2.5.0-alpha02
выпускается. Версия 2.5.0-Alpha02 содержит эти коммиты.
Изменения API
-
SavedStateHandle
иSavedStateViewModelFactory
были преобразованы в Котлин. Это улучшило нулясь дженериков в обоих классах. ( IB6CE2 , B/216168263 , I9647A , B/177667711 ) - Параметр функции
switchMap
LiveData
теперь может иметь нулевой выход. ( I40396 , B/132923666 ) - Расширения
LiveData
-Ktx теперь аннотируются@CheckResult
чтобы обеспечить соблюдение того, что результат используется при вызове этих функций. ( IA0F05 , B/207325134 )
Поведение изменяется
-
SavedStateHandle
теперь правильно хранит defaultValue, когда нет значения для указанного ключа. ( I1c6ce , b/178510877 )
Исправления ошибок
- От жизненного цикла
2.4.1
: обновленныйlifecycle-process
, чтобы зависеть от запуска 1.1.1 , чтобы гарантировать, что исправления, которые предотвращаютProcessLifecycleInitializer
от выбросаStartupException
доступны по умолчанию. ( IB01DF , B/216490724 ) - Теперь существует улучшенное сообщение об ошибке, когда пользовательские классы
AndroidViewModel
имеют параметры в неправильном порядке и пытаются создатьViewModel
. ( I340f7 , b/177667711 ) - Теперь вы можете создать модель представления через
CreationExtras
используяAndroidViewModelFactory
без установки приложения. ( I6ebef , b/217271656 )
Версия 2.5.0-Alpha01
26 января 2022 г.
androidx.lifecycle:lifecycle-*:2.5.0-alpha01
. Версия 2.5.0-Alpha01 содержит эти коммиты.
ViewModel CreationExtras
С помощью этого выпуска мы закладываем основу для реструктуризации, как строится ViewModel
. Вместо жесткого набора подклассов ViewModelProvider.Factory
, каждый из которых добавляет дополнительную функциональность (позволяя параметру конструктора Application
через AndroidViewModelFactory
, позволяя параметр конструктора SavedStateHandle
через SavedStateViewModelFactory
и AbstractSavedStateViewModelFactory
, мы перемещаем в течение всего мира. На новой концепции CreationExtras
. ( IA7343 , B/188691010 , B/188541057 )
С помощью этого изменения ViewModelProvider
больше не делает прямые вызовы в предыдущий метод create(Class<T>)
ViewModelProvider.Factory
. Вместо этого он вызывает новую перегрузку create
: create(Class<T>, CreationExtras)
. Это означает, что любая прямая реализация экземпляра ViewModelProvider.Factory
теперь имеет доступ к каждому из этих новых CreationExtras
:
-
ViewModelProvider.NewInstanceFactory.VIEW_MODEL_KEY
: этаString
предоставляет доступ к пользовательской ключу, которую вы передали вViewModelProvider.get()
. -
ViewModelProvider.AndroidViewModelFactory.APPLICATION_KEY
предоставляет доступ к классуApplication
. -
SavedStateHandleSupport.SAVED_STATE_REGISTRY_OWNER_KEY
предоставляет доступ кSavedStateRegistryOwner
, который используется для построения этой ViewModel. -
SavedStateHandleSupport.VIEW_MODEL_STORE_OWNER_KEY
предоставляет доступ кViewModelStoreOwner
, который используется для построения этой ViewModel. -
SavedStateHandleSupport.DEFAULT_ARGS_KEY
предоставляет доступ кBundle
аргументов, которые следует использовать для построенияSavedStateHandle
.
Эти дополнения предоставляются по умолчанию при использовании активности 1.5.0-alpha01
, фрагмент 1.5.0-alpha01
и навигация 2.5.0-alpha01
. Если вы используете более раннюю версию этих библиотек, CreationExtras
CreationExtras
будут пустыми - все существующие подклассы ViewModelProvider.Factory
были переписаны для поддержки обоих путей создания устаревшего идем вперед.
Эти CreationExtras
позволяют вам построить ViewModelProvider.Factory
, который передает только информацию, необходимую для каждой ViewModel
не полагаясь на строгую иерархию заводских подклассов:
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
}
}
Мы используем функцию расширения createSavedStateHandle()
на CreationExtras
от SavedStateHandleSupport
чтобы построить SavedStateHandle
только для одной ViewModel, которая нуждается в этом. ( IA6654 , B/188541057 )
Пользовательские CreationExtras
могут быть предоставлены, переопределяя getDefaultViewModelCreationExtras()
в вашей ComponentActivity
или Fragment
, что делает их доступными для вашего пользовательского ViewModelProvider.Factory
в качестве встроенной формы вспомогательной инъекции. Эти дополнения будут автоматически доступны для вашей пользовательской заводской завод при непосредственном использовании с ViewModelProvider
или при использовании by viewModels()
и by activityViewModels()
расширения свойств Kotlin. ( I79f2b , b/207012584 , b/207012585 , b/207012490 )
Исправления ошибок
- Исправлена проблема, в которой значение по умолчанию, предоставленное для
SavedStateHandle
появится после смерти и отдыха процесса, даже если оно было специально удалено изSavedStateHandle
. Как следствие этого,SavedStateHandle
больше не будет объединять значения по умолчанию и восстанавливать значения вместе, вместо этого используя только восстановленные значения в качестве источника истины. ( I53a4b )
Версия 2.4
Версия 2.4.1
9 февраля 2022 г.
androidx.lifecycle:lifecycle-*:2.4.1
выпущен. Версия 2.4.1 содержит эти коммиты.
Исправления ошибок
- Перекурированный из жизненного цикла
2.5.0-alpha01
: Исправлена проблема, в которой значение по умолчанию, предоставленное дляSavedStateHandle
будет повторно применять после смерти процесса и отдыха, даже если оно было специально удалено изSavedStateHandle
. Как следствие этого,SavedStateHandle
больше не будет объединять значения по умолчанию и восстанавливать значения вместе, вместо этого используя только восстановленные значения в качестве источника истины. ( I53a4b ) -
lifecycle-process
теперь зависит от стартапа Androidx 1.1.1 , который установил регрессию в том случае, где использованиеProcessLifecycleInitializer
может привестиStartupException
. ( B/216490724 )
Версия 2.4.0
27 октября 2021 г.
androidx.lifecycle:lifecycle-*:2.4.0
выпущен. Версия 2.4.0 содержит эти коммиты.
Важные изменения с 2.3.0
-
@OnLifecycleEvent
был устарел. Вместо этого следует использоватьLifecycleEventObserver
илиDefaultLifecycleObserver
. -
androidx.lifecycle:lifecycle-viewmodel-compose
. Он предоставляетviewModel()
Composable иLocalViewModelStoreOwner
.- Изменение источника :
ViewModelProvider
был переписан в Котлин.ViewModelProvider.Factory.create
Метод больше не допускает общий общий.
- Изменение источника :
- Новые API Coroutines были добавлены в
androidx.lifecycle:lifecycle-runtime-ktx
: -
Lifecycle.repeatOnLifecycle
, API, который выполняет блок кода в коратике, когда жизненный цикл, по крайней мере, в определенном состоянии. Блок отменит и повторно запускается, когда жизненный цикл движется в целевом состоянии и выходит из целевого состояния; -
Flow.flowWithLifecycle
, API, который излучает значения из восходящего потока, когда жизненный цикл, по крайней мере, в определенном состоянии. -
DefaultLifecycleObserver
был перемещен изlifecycle.lifecycle-common-java8
вlifecycle.lifecycle-common
.lifecycle.lifecycle-common-java8
больше неlifecycle.lifecycle-common
никаких дополнительных функциональных возможностей на вершинеlifecycle.lifecycle-common
. - Non Coroutines API из
lifecycle-viewmodel-ktx
были перемещены в модульlifecycle-viewmodel
. lifecycle-process
теперь используетandroidx.startup
для инициализацииProcessLifecycleOwner
.Ранее это делалось
androidx.lifecycle.ProcessLifecycleOwnerInitializer
.Если вы использовали
tools:node="remove"
ContentProvider
который используется для инициализации жизненного цикла процесса в прошлом, то вам нужно сделать следующее.<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
выпускается без изменений из жизненного цикла 2.4.0-бета01. Версия 2.4.0-RC01 содержит эти коммиты.
Версия 2.4.0-бета01
15 сентября 2021 г.
androidx.lifecycle:lifecycle-*:2.4.0-beta01
выпускается. Версия 2.4.0-бета01 содержит эти коммиты.
Изменения API
-
@OnLifecycleEvent
был устарел. Вместо этого следует использоватьLifecycleEventObserver
илиDefaultLifecycleObserver
. ( I5a8fa ) - DefaultLifeCycleObserver был перенесен из
androidx.lifecycle.lifecycle-common-java8
вandroidx.lifecycle.lifecycle-common
.androidx.lifecycle.lifecycle-common-java8
больше не предоставляет никаких дополнительных функциональных возможностей поверхandroidx.lifecycle.lifecycle-common
, поэтому зависимость от нее может быть заменена наandroidx.lifecycle.lifecycle-common
. ( I021AA ) - Non Coroutines API из
lifecycle-viewmodel-ktx
были перемещены в модульlifecycle-viewmodel
. ( I6d5b2 )
Внешний вклад
Версия 2.4.0-Alpha03
4 августа 2021 г.
androidx.lifecycle:lifecycle-*:2.4.0-alpha03
выпущен. Версия 2.4.0-Alpha03 содержит эти коммиты.
Изменения API
- Изменение источника : ViewModelProvider был переписан в Котлин.
ViewModelProvider.Factory.create
Метод больше не допускает общий общий. ( I9b9f6 )
Изменения поведения
-
Lifecycle.repeatOnLifecycle
:block
теперь всегда используется последовательно при повторении выполнения. ( IBAB33 )
Внешний вклад
- Спасибо Chao2zhang за исправление фрагментов кода в документации
repeatOnLifecycle
. #205 .
Версия 2.4.0-Alpha02
16 июня 2021 г.
androidx.lifecycle:lifecycle-*:2.4.0-alpha02
выпускается. Версия 2.4.0-Alpha02 содержит эти коммиты.
Новые возможности
- Добавлена новая проверка Lint
RepeatOnLifecycleWrongUsage
вlifecycle-runtime-ktx
, который обнаруживает, когдаrepeateOnLifecycle
неправильно используется вonStart()
илиonResume()
. ( 706078 , b/187887400 )
Изменения API
- API
LifecycleOwner.addRepeatingJob
удаляется в пользуLifecycle.repeatOnLifecycle
. ( I4a3a8 ) - Сделайте
ProcessLifecycleInitializer
Public, чтобы другойandroidx.startup.Initializer
S может использовать их в качестве зависимостей. ( I94C31 )
Исправления ошибок
- Исправлена проблема с проверкой LINT
NullSafeMutableLiveData
, когда в поле есть модификаторы. ( #147 , b/183696616 ) - Исправлена еще одна проблема с проверкой Lint
NullSafeMutableLiveData
Lint при использовании дженериков. ( #161 , b/184830263 )
Внешний вклад
- Спасибо Maxsav за улучшение чека
NullSafeMutableLiveData
Lint. ( #147 , b/183696616 ) - Спасибо Kozaxinan за улучшение чека
NullSafeMutableLiveData
Lint. ( #161 , b/184830263 )
Версия 2.4.0-Alpha01
24 марта 2021 г.
androidx.lifecycle:lifecycle-*:2.4.0-alpha01
выпускается. Версия 2.4.0-Alpha01 содержит эти коммиты.
Изменения поведения
lifecycle-process
теперь используетandroidx.startup
для инициализацииProcessLifecycleOwner
.Ранее это делалось
androidx.lifecycle.ProcessLifecycleOwnerInitializer
.Если вы использовали
tools:node="remove"
ContentProvider
который используется для инициализации жизненного цикла процесса в прошлом, то вам нужно сделать следующее.<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
- Добавлен API
Flow.flowWithLifecycle
, который излучает значения из потока вверх по течению, когда жизненный цикл, по крайней мере, в определенном состоянии с использованием APILifecycle.repeatOnLifecycle
. Это альтернатива также новойLifecycleOwner.addRepeatinJob
API. ( I0f4cd )
Исправления ошибок
- Из жизненного цикла 2.3.1 : правило Lint
NonNullableMutableLiveData
теперь может правильно различаться между полевыми переменными с различной нулямицией. ( B/169249668 )
Жизненный цикл ViewModel Compose Version 1.0.0
Версия 1.0.0-альфа07
16 июня 2021 г.
androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha07
. Версия 1.0.0-Alpha07 содержит эти коммиты.
Нарушение изменений API
-
viewModel()
теперь принимает дополнительнуюViewModelStoreOwner
, что облегчает работу с владельцами, отличными отLocalViewModelStoreOwner
. Например, теперь вы можете использоватьviewModel(navBackStackEntry)
, чтобы получить ViewModel, связанную с конкретным навигационным графиком. ( I2628d , B/188693123 )
Версия 1.0.0-альфа06
2 июня 2021 года
androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha06
. Версия 1.0.0-alpha06 содержит эти коммиты.
Обновлено, чтобы быть совместимым с Compose Version 1.0.0-beta08
.
Версия 1.0.0-альфа05
18 мая 2021 г.
androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha05
. Версия 1.0.0-alpha05 содержит эти коммиты.
Новые возможности
- Обновлено, чтобы быть совместимым с Compose Version
1.0.0-beta07
.
Исправления ошибок
- Файлы AndroidManifest из UI-test-Manifest и UI-Tooling-Data в настоящее время совместимы с Android 12 ( i6f9de , b/184718994 )
Версия 1.0.0-альфа04
7 апреля 2021 года
androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha04
. Версия 1.0.0-alpha04 содержит эти коммиты.
Изменения зависимости
- Эта версия позволяет
androidx.hilt:hilt-navigation-compose
иandroidx.navigation:navigation-compose
, чтобы синхронизировать зависимости отandroidx.compose.compiler:compiler:1.0.0-beta04
иandroidx.compose.runtime:runtime:1.0.0-beta04
. Для 1.0.0 требуется, чтобы компилятор и совпадение времени выполнения.
Версия 1.0.0-альфа03
10 марта 2021 г.
androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha03
. Версия 1.0.0-alpha03 содержит эти коммиты.
Изменения API
-
LocalViewModelStoreOwner.current
теперь возвращает нулевойViewModelStoreOwner
, чтобы лучше определить, доступен лиViewModelStoreOwner
в текущей композиции. API, которые требуютViewModelStoreOwner
, например,viewModel()
иNavHost
, все еще бросают исключение, если не установленViewModelStoreOwner
. ( IDF39a )
Версия 1.0.0.0.0.0.0.0.0.0.0.0.0.0.02
24 февраля 2021 г.
androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha02
. Версия 1.0.0-alpha02 содержит эти коммиты.
Изменения API
-
LocalViewModelStoreOwner
теперь имеетprovides
функции, которые можно использовать сCompositionLocalProvider
, заменив APIasProvidableCompositionLocal()
. ( I45d24 )
Жизненный цикл Viewmodel-Compose версии 1.0.0-Alpha01
10 февраля 2021 г.
androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha01
. Версия 1.0.0-alpha01 содержит эти коммиты.
Новые возможности
- Composable и
LocalViewModelStoreOwner
viewModel()
были перемещены изandroidx.compose.ui.viewinterop
этого артефакта в пакетеandroidx.lifecycle.viewmodel.compose
. ( I7a374 )
Версия 2.3.1
Жизненный цикл версии 2.3.1
24 марта 2021 г.
androidx.lifecycle:lifecycle-*:2.3.1
выпущен. Версия 2.3.1 содержит эти коммиты.
Исправления ошибок
- Правило Lint
NonNullableMutableLiveData
теперь может должным образом различать переменные поля с различной нулямицией. ( B/169249668 )
Версия 2.3.0
Версия 2.3.0
10 февраля 2021 г.
androidx.lifecycle:lifecycle-*:2.3.0
выпущен. Версия 2.3.0 содержит эти коммиты.
Основные изменения с 2.2.0
- Поддержка
SavedStateHandle
для неразовых классов :SavedStateHandle
теперь поддерживает ленивую сериализацию, позволяя вам позвонитьsetSavedStateProvider()
для данного ключа, предоставляяSavedStateProvider
, который получит обратный вызов дляsaveState()
, когдаSavedStateHandle
просят сохранить его состояние. См . Сохранение не-ласковых классов . - Содействие поведению жизненного цикла :
- LifeCyclereGistry в настоящее время обеспечивает соблюдение
DESTROYED
как терминальное государство. -
LifecycleRegistry
теперь проверяет, что ее методы вызываются в основной поток. Это всегда было требованием для жизненных циклов деятельности, фрагментов и т. Д. Добавление наблюдателей из неэ-мэльных потоков привело к трудностям в сбоях во время выполнения. Для объектовLifecycleRegistry
, которые принадлежат вашим собственным компонентам, вы можете явно отказаться от чеков, используяLifecycleRegistry.createUnsafe(...)
, но затем вы должны убедиться, что правильная синхронизация введена, когда доступна к этойLifecycleRegistry
.
- LifeCyclereGistry в настоящее время обеспечивает соблюдение
- Помогатели жизни и события жизненного цикла : добавлены статические вспомогательные методы
downFrom(State)
,downTo(State)
,upFrom(State)
,upTo(State)
вLifecycle.Event
для созданияEvent
с учетомState
и направления перехода. Добавлен методgetTargetState()
, который предоставляетState
, что жизненный цикл будет переходить непосредственно послеEvent
. -
withStateAtLeast
: Добавлен API-интерфейсLifecycle.withStateAtLeast
, которые ожидают состояния жизненного цикла и запускают не подвижный блок кодового синхронного в точке состояния, а затем возобновите с результатом. Эти API отличаются от существующихwhen*
, поскольку они не разрешают запуск приостановленного кода и не используют пользовательский диспетчер. ( AOSP/1326081 ) - API
ViewTree
: новыйViewTreeLifecycleOwner.get(View)
иViewTreeViewModelStoreOwner.get(View)
API позволяет получить содержащийLifecycleOwner
иViewModelStoreOwner
, соответственно, с учетом экземпляраView
. Вы должны перейти на действие1.2.0
и фрагмент1.3.0
, а также AppCompat 1.3.0-Alpha01 или выше, чтобы правильно заполнить это.findViewTreeLifecycleOwner
иfindViewTreeViewModelStoreOwner
Kotlin расширения доступны вlifecycle-runtime-ktx
иlifecycle-viewmodel-ktx
, соответственно. -
LiveData.observe()
Увеличение удлинения котлина : расширениеLiveData.observe()
Kotlin, необходимое для использования синтаксиса Lambda, теперь устарело, поскольку это не требуется при использовании Kotlin 1.4.
Версия 2.3.0-RC01
16 декабря 2020 г.
androidx.lifecycle:lifecycle-*:2.3.0-rc01
выпускается. Версия 2.3.0-RC01 содержит эти коммиты.
Исправления ошибок
- Метод
keys()
SavedStateHandle
теперь согласован до и после сохранения состояния - теперь он включает в себя клавиши, ранее используемые сsetSavedStateProvider()
в дополнение к ключам, используемым сset()
иgetLiveData()
. ( AOSP/1517919 , B/174713653 )
Внешний вклад
- API, чтобы приостановить коратики с учетом жизненного цикла, теперь лучше обрабатывают вызовы
yield()
. Спасибо Никлас Ансман Джурц! ( AOSP/1430830 , B/168777346 )
Версия 2.3.0-бета01
1 октября 2020 г.
androidx.lifecycle:lifecycle-*:2.3.0-beta01
выпускается. Версия 2.3.0-бета01 содержит эти коммиты.
Изменения API
- Расширение Kotlin
LiveData.observe()
необходимое для использования синтаксиса Lambda, теперь устарело, поскольку это не требуется при использовании Kotlin 1.4. ( I40d3f )
Исправления ошибок
- Обновление Androidx для использования Kotlin 1.4 ( ID6471 , B/165307851 , B/165300826 )
КОМЕНТАЦИЯ ИЗМЕНЕНИЯ
- Документы
liveData
Builder иasLiveData()
были обновлены, чтобы включить подробности об изменении заданных значений тайм -аута. ( AOSP/1122324 )
Версия 2.3.0-Alpha07
19 августа 2020 г.
androidx.lifecycle:lifecycle-*:2.3.0-alpha07
выпускается. Версия 2.3.0-Alpha07 содержит эти коммиты.
Исправления ошибок
- Исправлена проблема с аварией в чек на
NullSafeMutableLiveData
lint. ( AOSP/1395367 )
Версия 2.3.0-Alpha06
22 июля 2020 г.
androidx.lifecycle:lifecycle-*:2.3.0-alpha06
выпускается. Версия 2.3.0-Alpha06 содержит эти коммиты.
Новые возможности
- Добавлены статические вспомогательные методы
downFrom(State)
,downTo(State)
Event
upFrom(State)
,upTo(State)
State
Lifecycle.Event
. Добавлен методgetTargetState()
, который предоставляетState
, что жизненный цикл будет переходить непосредственно послеEvent
. ( I00887 ) - Добавлен API-интерфейс
Lifecycle.withStateAtLeast
, которые ожидают состояния жизненного цикла, и запускают не подвижный блок кода синхронно в точке изменения состояния, затем возобновите с результатом. Эти API отличаются от существующихwhen*
, поскольку они не разрешают запуск приостановленного кода и не используют пользовательский диспетчер. ( AOSP/1326081 )
Изменения поведения
- LifeCyclereGistry в настоящее время обеспечивает соблюдение
DESTROYED
как терминальное государство. ( I00887 ) -
LifecycleRegistry
теперь проверяет, что ее методы вызываются в основной поток. Это всегда было требованием для жизненных циклов деятельности, фрагментов и т. Д. Добавление наблюдателей из неэ-мэльных потоков привело к трудностям в сбоях во время выполнения. Для объектовLifecycleRegistry
, которые принадлежат вашим собственным компонентам, вы можете явно отказаться от проверки, используяLifecycleRegistry.createUnsafe(...)
, но затем вы должны убедиться, что соответствующая синхронизация введена, когда этаLifecycleRegistry
доступна из разных потоков ( IE7280 , B/137392809 )
Исправления ошибок
- Исправлена авария в
NullSafeMutableLiveData
. ( B/159987480 ) - Исправлена
ObsoleteLintCustomCheck
для чеков с ворсом, связанными сlifecycle-livedata-core-ktx
(и, в частности,NullSafeMutableLiveData
). ( B/158699265 )
Версия 2.3.0-Alpha05
24 июня 2020 г.
androidx.lifecycle:lifecycle-*:2.3.0-alpha05
выпускается. Версия 2.3.0-Alpha05 содержит эти коммиты.
Исправления ошибок
-
LiveData
теперь лучше обрабатывает случаи повторного въезда, избегая дублирующих вызововonActive()
илиonInactive()
. ( B/157840298 ) - Исправлена проблема, когда проверки Lint не будут работать при использовании Android Studio 4.1 Canary 6 или выше. ( AOSP/1331903 )
Версия 2.3.0-Alpha04
10 июня 2020 г.
androidx.lifecycle:lifecycle-*:2.3.0-alpha04
выпускается. Версия 2.3.0-Alpha04 содержит эти коммиты.
Исправления ошибок
- Исправлена авария в проверке LINT
NonNullableMutableLiveData
. ( B/157294666 ) - Проверка Lint
NonNullableMutableLiveData
теперь охватывает значительно больше случаев, когда наMutableLiveData
было установлено значениеnull
значения с параметрам не нулевого типа. ( б/156002218 )
Версия 2.3.0-Alpha03
20 мая 2020 г.
androidx.lifecycle:lifecycle-*:2.3.0-alpha03
выпускаются. Версия 2.3.0-Alpha03 содержит эти коммиты.
Новые возможности
-
SavedStateHandle
теперь поддерживает ленивую сериализацию, позволяя вам вызоватьsetSavedStateProvider()
для данного ключа, предоставляяSavedStateProvider
, который получит обратный вызовsaveState()
когдаSavedStateHandle
просят сохранить его состояние. ( B/155106862 ) - Новый API
ViewTreeViewModelStoreOwner.get(View)
позволяет получить содержащийViewModelStoreOwner
, данный экземплярView
. Вы должны перейти на активность1.2.0-alpha05
, фрагмент1.3.0-alpha05
и Appcompat1.3.0-alpha01
, чтобы правильно заполнить это. Расширение KotlinfindViewModelStoreOwner()
было добавлено вlifecycle-viewmodel-ktx
. ( AOSP/1295522 )
Исправления ошибок
- Исправлена проблема, которая привела к тому, что чеки Lint
MutableLiveData
, выпущенные в жизненном цикле2.3.0-alpha01
были опубликованы вместе с артефактомlifecycle-livedata-core-ktx
. ( B/155323109 )
Версия 2.3.0-Alpha02
29 апреля 2020 г.
androidx.lifecycle:lifecycle-*:2.3.0-alpha02
выпускается. Версия 2.3.0-Alpha02 содержит эти коммиты.
Изменения API
-
SavedStateViewModelFactory
теперь позволяет вам передавать нулевоеApplication
к своему конструктору для лучшей поддержки случаев, когда кто -то недоступен, и поддержкаAndroidViewModel
не нужна. ( AOSP/1285740 )
Исправления ошибок
- Улучшенная производительность холодного запуска, избегая сбоя проверки класса на API 28 и нижних устройствах. ( AOSP/1282118 )
Версия 2.3.0-Alpha01
4 марта 2020 г.
androidx.lifecycle:lifecycle-*:2.3.0-alpha01
выпускается. Версия 2.3.0-Alpha01 содержит эти коммиты.
Новые возможности
- Новый API
ViewTreeLifecycleOwner.get(View)
позволяет получить содержащийLifecycleOwner
учитывая экземплярView
. Вы должны перейти на действие1.2.0-alpha01
и фрагмент1.3.0-alpha01
чтобы правильно заполнить это.findViewTreeLifecycleOwner
Kotlin Extension доступен вlifecycle-runtime-ktx
. ( AOSP/1182361 , AOSP/1182956 ) - Добавлена новая проверка Lint, которая предупреждает вас при установлении
null
значения наMutableLiveData
, которая была определена в Котлине как не нулевой. Это доступно при использовании артефактовlivedata-core-ktx
илиlivedata-ktx
. ( aosp/1154723 , aosp/1159092 ) - A new
lifecycle-runtime-testing
artifact is available that provides aTestLifecycleOwner
that implementsLifecycleOwner
and provides a thread safe mutableLifecycle
. ( aosp/1242438 )
Исправления ошибок
- The
lifecycle-runtime
artifact now has a unique package name. ( aosp/1187196 )
Version 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
.
Version 2.2.0
January 22, 2020
androidx.lifecycle:lifecycle-*:2.2.0
is released. Version 2.2.0 contains these commits .
Important changes since 2.1.0
- Lifecycle Coroutine Integration : The new
lifecycle-runtime-ktx
artifact adds integration between Lifecycle and Kotlin coroutines. Thelifecycle-livedata-ktx
has 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 aFragment
orFragmentActivity
to the newViewModelProvider(ViewModelStoreOwner)
constructor to achieve the same functionality when using Fragment1.2.0
. -
lifecycle-extensions
Artifact Deprecation : With the above deprecation ofViewModelProviders.of()
, this release marks the deprecation of the last API inlifecycle-extensions
and this artifact should now be considered deprecated in its entirety. We strongly recommend depending on the specific Lifecycle artifacts you need (such aslifecycle-service
if you're usingLifecycleService
andlifecycle-process
if you're usingProcessLifecycleOwner
) rather thanlifecycle-extensions
as there will not be a future2.3.0
release 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
DefautLifecycleObserver
instead; 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
ViewModel
was stored inViewModelStore
and queried later with default factory. - Fix a usage of
Dispatchers.Main.immediate
inlaunchWhenCreated
and similar methods to be called synchronously during corresponding lifecycle event. ( aosp/1156203 )
External contributions
- 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 )
Version 2.2.0-rc01
October 23, 2019
androidx.lifecycle:lifecycle-*:2.2.0-rc01
is released. Version 2.2.0-rc01 contains these commits .
Исправления ошибок
- Fixed an issue where
launchWhenCreated
and related methods would run one frame later than the associated lifecycle method due to its use ofDispatchers.Main
instead ofDispatchers.Main.immediate
. ( aosp/1145596 )
External contributions
- Thanks to Nicklas Ansman for contributing the fix! ( aosp/1145596 )
Version 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
ProcessLifecycleOwner
and the activity'sLifecycleOwner
moving to started and resumed on Android 10 devices. ( aosp/1128132 ) - Fixed a regression introduced in Lifecycle
2.2.0-alpha05
which would cause aNullPointerException
when using version2.0.0
or2.1.0
oflifecycle-process
. ( b/141536990 )
Version 2.2.0-alpha05
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 ofliveData
now useDispatchers.Main.immediate
instead ofDispatchers.Main
. ( b/139740492 )
External contributions
- 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
ViewModelStoreOwner
can now optionally implementHasDefaultViewModelProviderFactory
to 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 aFragment
orFragmentActivity
to the newViewModelProvider(ViewModelStoreOwner)
constructor to achieve the same functionality. ( aosp/1009889 )
Version 2.2.0-alpha02
2 июля 2019 г.
androidx.lifecycle:*:2.2.0-alpha02
is released. The commits included in this version can be found here .
Изменения API
- Replaced
LiveDataScope.initialValue
withLiveDataScope.latestValue
which will track the current emitted value of theliveData
block. - Added a new overload to the
liveData
builder that receivestimeout
parameter as typeDuration
Version 2.2.0-alpha01
May 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
Version 1.0.0
January 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
ViewModel
classes to access and to contribute to the saved state. This object can be received in constructor ofViewModel
class and factories provided by default by Fragments and AppCompatActivity will injectSavedStateHandle
automatically. - AbstractSavedStateViewModelFactory was added. It allows you to create custom factories for your
ViewModel
and 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
October 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
IllegalStateException
when usingAbstractSavedStateViewModelFactory
. ( b/141225984 )
ViewModel-SavedState Version 1.0.0-alpha05
18 сентября 2019 г.
androidx.lifecycle:lifecycle-viewmodel-savedstate:1.0.0-alpha05
is released. Версия 1.0.0-alpha05 содержит эти коммиты .
Изменения API
-
SavedStateViewModelFactory
no longer extendsAbstractSavedStateViewModelFactory
andSavedStateHandle
is 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-savedstate
no longer depends onfragment
and the relatedSavedStateViewModelFactory(Fragment)
andSavedStateViewModelFactory(FragmentActivity)
constructors have been removed. Instead,SavedStateViewModelFactory
is 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
-
SavedStateVMFactory
is renamed toSavedStateViewModelFactory
. -
AbstractSavedStateVMFactory
is 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
ViewModels
can contribute to savedstate. To do that you use newly introduced viewmodel's factorySavedStateVMFactory
and your ViewModel should have a constructor that receivesSavedStateHandle
object as a parameter.
Version 2.1.0
Important changes since 2.0.0
- Added
LifecycleEventObserver
for the cases when a stream of lifecycle events is needed. It is a public API instead of a hiddenGenericLifecycleObserver
class. - Added ktx extensions for
LiveData.observe
methods andTransformations.*
methods. - Added
Transformations.distinctUntilChanged
, which creates a new LiveData object that does not emit a value until the sourceLiveData
value has been changed. - Added coroutine support in ViewModels by adding the extension property
ViewModel.viewModelScope
.
Version 2.1.0
5 сентября 2019 г.
androidx.lifecycle:lifecycle-*:2.1.0
is released. The commits included in this version can be found here .
Version 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 .
Version 2.1.0-beta01
May 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
liveData
extension functions for transformations and observations,ViewModel
initialisation with property delegation and others are stabilised and not going to change.
Version 2.1.0-alpha04
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 aViewModelStore
directly, rather than only aViewModelStoreOwner
. ( aosp/932932 )
Version 2.1.0-alpha03
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.KeyedFactory
was removed. Second interface in addition toViewModelProvider.Factory
didn't compose well with new features as property delegation in Kotlinby viewmodels {}
. ( aosp/914133 )
Version 2.1.0-alpha02
January 30, 2019
androidx.lifecycle 2.1.0-alpha02
is released.
Изменения API
-
LifecycleRegistry
now contains asetCurrentState()
method that replaces the now deprecatedsetState()
method. ( aosp/880715 )
Исправления ошибок
- Fixed an issue where mock
ViewModel
instances would crash when the containingViewModelStore
was cleared. b/122273087
Version 2.1.0-alpha01
December 17, 2018
androidx.lifecycle 2.1.0-alpha01
is released.
Новые возможности
- Added
LifecycleEventObserver
for the cases when a stream of lifecycle events is needed. It is a public api instead of a hiddenGenericLifecycleObserver
class. - Added ktx extensions for
LiveData.observe
methods andTransformations.*
methods. - Method
Transformations.distinctUntilChanged
was added. It creates a newLiveData
object that does not emit a value until the source LiveData value has been changed. - Coroutine support in ViewModels: extension property
ViewModel.viewModelScope
was added. - Added
ViewModelProvider.KeyedFactory
, a factory for ViewModels that receiveskey
andClass
increate
method.
Version 2.0.0
Version 2.0.0
September 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
Version 2.0.0-beta01
July 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
March 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 г.
Packaging Changes
New, much smaller dependencies are now available:
-
android.arch.lifecycle:livedata:1.1.0
-
android.arch.lifecycle:viewmodel:1.1.0
Изменения API
- The deprecated
LifecycleActivity
andLifecycleFragment
have now been removed - please useFragmentActivity
,AppCompatActivity
or supportFragment
. -
@NonNull
annotations have been added toViewModelProviders
andViewModelStores
-
ViewModelProviders
constructor has been deprecated - please use its static methods directly -
ViewModelProviders.DefaultFactory
has been deprecated - please useViewModelProvider.AndroidViewModelFactory
- The static
ViewModelProvider.AndroidViewModelFactory.getInstance(Application)
method has been added to retrieve a staticFactory
suitable for creatingViewModel
andAndroidViewModel
instances.
Жизненный цикл
This table lists all the artifacts in the androidx.lifecycle
group.
Артефакт | Стабильный выпуск | Кандидат на выпуск | Бета-версия | Альфа-релиз |
---|---|---|---|---|
жизненный цикл-* | 2.8.6 | - | - | 2.9.0-alpha03 |
lifecycle-viewmodel-compose | 2.8.6 | - | - | 2.9.0-alpha03 |
Объявление зависимостей
To add a dependency on Lifecycle, you must add the Google Maven repository to your project. Для получения дополнительной информации прочтите репозиторий Google Maven .
Добавьте зависимости для нужных вам артефактов в файл build.gradle
для вашего приложения или модуля:
Котлин
классный
dependencies { def lifecycle_version = "2.8.7" 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" // 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.8.7" 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") // 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.8.7" 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.8.7" 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") }
For more information about dependencies, see Add Build Dependencies .
Обратная связь
Ваши отзывы помогают сделать Jetpack лучше. Дайте нам знать, если вы обнаружите новые проблемы или у вас есть идеи по улучшению этой библиотеки. Пожалуйста, ознакомьтесь с существующими проблемами в этой библиотеке, прежде чем создавать новую. Вы можете добавить свой голос к существующей проблеме, нажав кнопку со звездочкой.
Дополнительную информацию см . в документации по системе отслеживания проблем .
Version 2.9
Version 2.9.0-alpha03
18 сентября 2024 г.
androidx.lifecycle:lifecycle-*:2.9.0-alpha03
is released. Version 2.9.0-alpha03 contains these commits .
Исправления ошибок
- From Lifecycle
2.8.6
: TheNullSafeMutableLiveData
Lint error has improved support for smart casts, avoiding false positives. ( 85fed6 , b/181042665 )
Обновления зависимостей
- From Lifecycle
2.8.6
: Lifecycle Runtime Compose now depends on Compose Runtime1.7.1
- Lifecycle Runtime now depends on ProfileInstaller
1.4.0
Version 2.9.0-alpha02
4 сентября 2024 г.
androidx.lifecycle:lifecycle-*:2.9.0-alpha02
is released. Version 2.9.0-alpha02 contains these commits .
Исправления ошибок
- From Lifecycle
2.8.5
: Update theandroidx.lifecycle.ReportFragment
ProGuard rules to allow obfuscation . ( ff898e1 )
Внешний вклад
- Move
androidx.compose.ui.platform.LocalLifecycleOwner
to common source set (KMP). Thanks Ivan Matkov from JetBrains for the contribution. ( 8cd5d03 ) - From Lifecycle
2.8.5
: SavedStateHandle.saveable` extension delegate now supports nullable values. Thanks Roman Kalukiewicz for the contribution. ( 0d78ea6 )
Version 2.9.0-alpha01
7 августа 2024 г.
androidx.lifecycle:lifecycle-*:2.9.0-alpha01
is released. Version 2.9.0-alpha01 contains these commits .
Kotlin Multiplatform
-
lifecycle-testing
is now KMP compatible. ( Iea41e ) - Add support for
linuxArm64
kotlin multiplatform target ( I139d3 , b/338268719 )
Новые возможности
- A new
androidx.lifecycle:lifecycle-viewmodel-testing
KMP artifact is available that provides aViewModelScenario
class for testing ViewModels in isolation, with support foronCleared
(all platforms) andSavedStateHandle
(Android only). ( 337f68d , c9b3409 , 9799a95c , b/264602919 ) - Creating a
ViewModel
withViewModelProvider
is now thread safe;@MainThread
annotations have been removed. ( Ifd978 , b/237006831 )
Изменения API
- Add the
CreationExtras.Key()
factory function to simplify the creation of anonymousCreationExtras.Key
objects. ( I970ee ) -
CreationExtras
now includes map-like operator overloads to enable idiomatic manipulation of content in Kotlin. It allows the use ofin
,+=
, and+
withCreationExtras
. ( Ib4353 ) -
CreationExtras
now implementsequals
,hashCode
, andtoString
methods. ( Ib4353 ) -
NewInstanceFactory
is now available on JVM Desktop and Android targets. ( d3d0892 ) - Inline extension property to expose underlying Application safely in Kotlin language version 2.0 ( I39df2 )
Исправления ошибок
- Removed manual outlining of access to new platform APIs since this happens automatically via API modeling when using R8 with AGP 7.3 or later (eg R8 version 3.3) and for all builds when using AGP 8.1 or later (eg D8 version 8.1). Clients who are not using AGP are advised to update to D8 version 8.1 or later. See this article for more details. ( If6b4c , b/345472586 )
Version 2.8
Version 2.8.6
18 сентября 2024 г.
androidx.lifecycle:lifecycle-*:2.8.6
is released. Version 2.8.6 contains these commits .
Исправления ошибок
- The
NullSafeMutableLiveData
Lint error has improved support for smart casts, avoiding false positives. ( 85fed6 , b/181042665 )
Обновления зависимостей
- Lifecycle Runtime Compose now depends on Compose Runtime
1.7.1
Version 2.8.5
4 сентября 2024 г.
androidx.lifecycle:lifecycle-*:2.8.5
is released. Version 2.8.5 contains these commits .
Исправления ошибок
- Update the
androidx.lifecycle.ReportFragment
ProGuard rules to allow obfuscation . ( ff898e1 )
Внешний вклад
-
SavedStateHandle.saveable
extension delegate now supports nullable values. Thanks Roman Kalukiewicz for the contribution. ( 0d78ea6 )
Version 2.8.4
24 июля 2024 г.
androidx.lifecycle:lifecycle-*:2.8.4
is released. Version 2.8.4 contains these commits .
Исправления ошибок
-
LiveData.asFlow()
now correctly handles cases where the returned Flow is immediately completed after receiving a value already set on theLiveData
(for example, when usingtake(1)
). ( I9c566 ) -
Lifecycle*Effect
completion is now idempotent (ie, if theonStopOrDispose
was called because of the Lifecycle being stopped, it won't be called a second time upon disposal unless the Lifecycle goes back up toSTARTED
again). ( I5f607 , b/352364595 )
Version 2.8.3
1 июля 2024 г.
androidx.lifecycle:lifecycle-*:2.8.3
is released. Version 2.8.3 contains these commits .
Исправления ошибок
- Fixed an issue with Lifecycle 2.8's backward compatibility with Compose 1.6.0 and lower when using code shrinking. ( aosp/3133056 , b/346808608 )
Version 2.8.2
12 июня 2024 г.
androidx.lifecycle:lifecycle-*:2.8.2
is released. Version 2.8.2 contains these commits .
Исправления ошибок
- Fixed
CompositionLocal LocalLifecycleOwner not present
errors when using Lifecycle 2.8.X with Compose 1.6.X or earlier - you can now use Lifecycle 2.8.2 with any version of Compose without any workarounds required. ( aosp/3105647 , b/336842920 ) -
ViewModelProvider
will no longer crash when mixing previous versions ofcompileOnly
Lifecycle dependencies with versions 2.8+, fixing issues with libraries such as LeakCanary. ( I80383 , b/341792251 )
Version 2.8.1
29 мая 2024 г.
androidx.lifecycle:lifecycle-*:2.8.1
is released. Version 2.8.1 contains these commits .
Исправления ошибок
-
lifecycle-viewmodel-compose
now only has a common dependency oncompose-runtime
, removing its common dependency oncompose-ui
. The Android artifact retains itscompose-ui
for compatibility. ( aosp/3079334 , b/339562627 ) -
ViewModel
'ssaveable
integration using property delegates now uses the class name as part of the auto-generated key, avoiding conflicts if multiple classes use the sameSavedStateHandle
. ( aosp/3063463 )
Version 2.8.0
14 мая 2024 г.
androidx.lifecycle:lifecycle-*:2.8.0
is released. Version 2.8.0 contains these commits .
Important changes since 2.7.0
-
LocalLifecycleOwner
has been moved from Compose UI tolifecycle-runtime-compose
so that its Compose-based helper APIs can be used outside of Compose UI. - The
lifecycle-runtime-compose
artifact now contains thedropUnlessResumed
anddropUnlessStarted
APIs which allow you to drop click or other events that occur even after theLifecycleOwner
has dropped below the givenLifecycle.State
. For example, this can be used with Navigation Compose to avoid handling click events after a transition to another screen has already begun:onClick: () -> Unit = dropUnlessResumed { navController.navigate(NEW_SCREEN) }
ViewModel.viewModelScope
is now an overridable constructor parameter, allowing you to inject your own dispatcher andSupervisorJob()
or to override the default by using thebackgroundScope
available withinrunTest
. ( 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
has been rewritten in Kotlin and now usesAutoClosable
instead ofCloseable
. It now supports addingAutoCloseable
objects with akey
that allows retrieving them viagetCloseable()
.Calling
LifecycleStartEffect
andLifecycleResumeEffect
without a key is now an error, following the same convention as theDisposableEffect
API that these APIs mirror.Deprecated
LiveDataReactiveStreams.toPublisher(lifecycleOwner, liveData)
in favor ofLiveData.toPublisher(lifecycleOwner)
.The
lifecycle-livedata-core-ktx
kotlin extensions have now been moved to thelifecycle-livedata-core
module.The
NullSafeMutableLiveData
has been refactored to avoid many false positives.
Lifecycle Kotlin Multiplatform Compatibility
The core Lifecycle APIs in Lifecycle
, LifecycleOwner
, LifecycleObserver
, Lifecycle.State
, Lifecycle.Event
, and LifecycleRegistry
are now shipped in artifacts compatible with Kotlin Multiplatform.
Artifacts impacted:
-
lifecycle-common
moves most APIs tocommon
and supports jvm and iOS in addition to Android. -
lifecycle-runtime
moves most APIs tocommon
and supports jvm and iOS in addition to Android. -
lifecycle-runtime-ktx
is now empty, with all APIs being moved intolifecycle-runtime
. -
lifecycle-runtime-compose
moves all APIs tocommon
and ships an Android artifact, matching the multiplatform support ofandroidx.compose
.
ViewModel Kotlin Multiplatform Compatibility
The lifecycle-viewmodel
artifact and APIs like ViewModel
, ViewModelStore
, ViewModelStoreOwner
, and ViewModelProvider
are now shipped in artifacts compatible with Kotlin Multiplatform.
To accommodate this change, methods such as those on ViewModelProvider
that took a java.lang.Class<T>
now have an equivalent method that takes a kotlin.reflect.KClass<T>
.
Binary compatibility on Android has been maintained, but there are a few notable changes when comparing the Android API surface to the common API surface:
- Constructing a
ViewModelProvider
instance is now done through theViewModelProvider.create()
methods rather than directly calling its constructor. -
ViewModelProvider.NewInstanceFactory
andViewModelProvider.AndroidViewModelFactory
are only available on Android.- Custom Factories are recommended to extend from
ViewModelProvider.Factory
and use thecreate
method that takes aCreationExtras
or use theviewModelFactory
Kotlin DSL.
- Custom Factories are recommended to extend from
- Using
ViewModelProvider
without a custom factory on non-JVM platforms will result in anUnsupportedOperationException
. On JVM platforms, compatibility is preserved by using the no-args ViewModel constructor if a custom factory is not provided. -
viewModelScope
will fallback to anEmptyCoroutineContext
in platforms whereDispatchers.Main
is not available (eg, Linux).
Artifacts impacted:
-
lifecycle-viewmodel
moves most APIs tocommon
and supports jvm and iOS in addition to Android. -
lifecycle-viewmodel-ktx
is now empty, with all APIs being moved intolifecycle-viewmodel
. -
lifecycle-viewmodel-compose
moves all APIs tocommon
and ships an Android artifact, matching the multiplatform support ofandroidx.compose
.
Изменения поведения
-
InitializerViewModelFactory
(includingviewModelFactory
builder function) will now throw anIllegalArgumentException
if ainitializer
with the sameclazz: KClass<VM : ViewModel>
has already been added. ( Ic3a36 )
Известные проблемы
-
lifecycle-*:2.8.0
requires a minimum Compose version of 1.7.0-alpha05 ( b/336842920 ).
Version 2.8.0-rc01
1 мая 2024 г.
androidx.lifecycle:lifecycle-*:2.8.0-rc01
is released. Version 2.8.0-rc01 contains these commits .
Исправления ошибок
- Fixed an issue where the Baseline Profile for
lifecycle-common
classes was not properly packaged. These are now packaged in thelifecycle-runtime
AAR. ( aosp/3038274 , b/322382422 ) - Fixed an unintentional ordering change in how
AutoCloseable
instances attached to a ViewModel are cleared - the previous order ofaddCloseable(String, AutoCloseable)
, thenaddClosable(AutoCloseable)
, thenonCleared()
has been restored. ( aosp/3041632 ) - Improve the default creation behavior for
viewModelScope
for native and JVM Desktop environments. ( aosp/3039221 )
Внешний вклад
- Thanks Victor Kropp for improving the checking for the main thread on JVM Desktop. ( aosp/3037116 )
Version 2.8.0-beta01
17 апреля 2024 г.
androidx.lifecycle:lifecycle-*:2.8.0-beta01
is released. Version 2.8.0-beta01 contains these commits .
Новые возможности
- The
lifecycle-runtime-compose
artifact is now compatible with Kotlin Multiplatform, moving its code tocommon
and ships an Android artifact, matching the multiplatform support forandroidx.compose
. ( If7a71 , I4f4a0 , b/331769623 )
Version 2.8.0-alpha04
3 апреля 2024 г.
androidx.lifecycle:lifecycle-*:2.8.0-alpha04
is released. Version 2.8.0-alpha04 contains these commits .
Новые возможности
- The
lifecycle-viewmodel-compose
artifact is now compatible with Kotlin Multiplatform, moving its code tocommon
and ships an Android artifact, matching the multiplatform support ofandroidx.compose
. The accommodate this change, the ComposableviewModel
method now accepts aKClass
in addition to ajava.lang.Class
. ( b/330323282 )
Исправления ошибок
- The
NullSafeMutableLiveData
has been refactored to avoid many false positives. ( I2d8c1 , Iafb18 , I03463 , I7ecef )
Dependency update
- The
lifecycle-viewmodel-compose
artifact now depends on Compose 1.6.0. - Lifecycle now depends on Profile Installer 1.3.1 .
Version 2.8.0-alpha03
20 марта 2024 г.
androidx.lifecycle:lifecycle-*:2.8.0-alpha03
is released. Version 2.8.0-alpha03 contains these commits .
Новые возможности
ViewModel.viewModelScope
is now an overridable constructor parameter, allowing you to inject your own dispatcher andSupervisorJob()
or to override the default by using thebackgroundScope
available withinrunTest
. ( 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 Multiplatform Compatibility
The lifecycle-viewmodel
artifact and APIs like ViewModel
, ViewModelStore
, ViewModelStoreOwner
, and ViewModelProvider
are now shipped in artifacts compatible with Kotlin Multiplatform. ( b/214568825 )
To accommodate this change, methods such as those on ViewModelProvider
that took a java.lang.Class<T>
now have an equivalent method that takes a kotlin.reflect.KClass<T>
.
Binary compatibility on Android has been maintained, but there are a few notable changes when comparing the Android API surface to the common API surface:
- Constructing a
ViewModelProvider
instance is now done through theViewModelProvider.create()
methods rather than directly calling its constructor. -
ViewModelProvider.NewInstanceFactory
andViewModelProvider.AndroidViewModelFactory
are only available on Android.- Custom Factories are recommended to extend from
ViewModelProvider.Factory
and use thecreate
method that takes aCreationExtras
or use theviewModelFactory
Kotlin DSL.
- Custom Factories are recommended to extend from
- Using
ViewModelProvider
without a custom factory on non-JVM platforms will result in anUnsupportedOperationException
. On JVM platforms, compatibility is preserved by using the no-args ViewModel constructor if a custom factory is not provided. -
viewModelScope
will fallback to anEmptyCoroutineContext
in platforms whereDispatchers.Main
is not available (eg, Linux).
Изменения поведения
-
InitializerViewModelFactory
(includingviewModelFactory
builder function) will now throw anIllegalArgumentException
if ainitializer
with the sameclazz: KClass<VM : ViewModel>
has already been added. ( Ic3a36 )
Исправления ошибок
-
ViewModel.getCloseable
now handles duplicated keys: if thekey
already has anAutoCloseable
resource associated with it, the old resource will be replaced and closed immediately. ( Ibeb67 ) - Accessing the
viewModelScope
of aViewModel
is now thread safe. ( If4766 , b/322407038 )
Внешний вклад
-
LocalLifecycleOwner
moved from Compose UI to lifecycle-runtime-compose so that its Compose-based helper APIs can be used outside of Compose UI. Thanks Jake Wharton for the contribution. ( I6c41b , b/328263448 )
Version 2.8.0-alpha02
21 февраля 2024 г.
androidx.lifecycle:lifecycle-*:2.8.0-alpha02
is released. Version 2.8.0-alpha02 contains these commits.
Новые возможности
- The
dropUnlessResumed
anddropUnlessStarted
APIs have been added which allow you to drop click or other events that occur even after theLifecycleOwner
has dropped below the givenLifecycle.State
. For example, this can be used with Navigation Compose to avoid handling click events after a transition to another screen has already begun:onClick: () -> Unit = dropUnlessResumed { navController.navigate(NEW_SCREEN) }
( Icba83 , b/317230685 )
Kotlin Conversions
-
ViewModel
is now written in Kotlin ( I16f26 , b/214568825 ) - The
lifecycle-viewmodel-ktx
kotlin extensions have now been moved to the base lifecycle module. ( Id787b , b/274800183 ) - The
lifecycle-runtime-ktx
kotlin extensions have now been moved to the base lifecycle module. ( Ic3686 , b/274800183 ) - The
lifecycle-livedata-core-ktx
kotlin extensions have now been moved to the base lifecycle module. ( I54a3d , b/274800183 )
Kotlin Multiplatform Compatibility
- The core Lifecycle APIs in
Lifecycle
,LifecycleOwner
,LifecycleObserver
,Lifecycle.State
,Lifecycle.Event
, andLifecycleRegistry
are now shipped in artifacts compatible with Kotlin Multiplatform. ( b/317249252 )
Изменения API
- Calling
LifecycleStartEffect
andLifecycleResumeEffect
without a key is now an error, following the same convention as theDisposableEffect
API that these APIs mirror. ( Ib0e0c , b/323518079 ) -
ViewModel
now usesAutoCloseable
instead ofCloseable
. That is a backward compatible change. ( I27f8e , b/214568825 ) - Deprecated
LiveDataReactiveStreams.toPublisher(lifecycleOwner, liveData)
in favor ofLiveData.toPublisher(lifecycleOwner)
. ( Iabe29 , b/262623005 )
Внешний вклад
- Thanks Ivan Matkov from Jetbrains for helping move Lifecycle to Kotlin Multiplatform. ( aosp/2926690 , I0c5ac , If445d )
Version 2.8.0-alpha01
24 января 2024 г.
androidx.lifecycle:lifecycle-*:2.8.0-alpha01
is released. Version 2.8.0-alpha01 contains these commits.
Новые возможности
-
ViewModel
now supports addingCloseable
objects with akey
that allows retrieving them viagetCloseable()
. ( I3cf63 )
Version 2.7
Version 2.7.0
10 января 2024 г.
androidx.lifecycle:lifecycle-*:2.7.0
is released. Version 2.7.0 contains these commits.
Important changes since 2.6.0
-
TestLifecycleOwner
now includes a suspending functionsetCurrentState()
which ensures that the state change and allLifecycleObserver
callbacks are completed before returning. Notably, unlike setting thecurrentState
property directly, this does not userunBlocking
, making it safe to use within a coroutine such as one provided byrunTest
. - The
LiveData
extensions ofmap
andswitchMap
now mirror the behavior ofdistinctUntilChanged
- if theLiveData
has avalue
set, themap
/switchMap
function will be immediately called to populate thevalue
of the returnedLiveData
. This ensures that the initial value will be set as part of the first composition (when used withobserveAsState()
), but does not change the observation behavior - updates values from the sourceLiveData
will still only apply once you start observing theLiveData
. - This release fixes an issue where
SavedStateHandle
would not properly restore customParcelable
classes 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
, andgetStateFlow
now specifically calls this limitation out. - The proguard keep rules associated with
LifecycleObserver
have been removed. This means that proguarded code that wishes to use APIs via reflection (such as using the long since deprecated@OnLifecycleEvent
annotation) 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 aFlow
ofLifecycle.Event
via theLifecycle.asFlow()
extension method. - Jetpack Compose users can now use
LifecycleEventEffect
to 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
LifecycleStartEffect
andLifecycleResumeEffect
to handle pairs of events - started to stopped and resumed to paused, respectively. This API mirrors the one found inDisposableEffect
and 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.State
can now be observed via theLifecycle.currentStateFlow
property, which returns aStateFlow
where thevalue
is the currentLifecycle.State
. - Jetpack Compose users can use the
Lifecycle.currentStateAsState()
extension to directly exposeLifecycle.State
as ComposeState
. This is equivalent (and a shorter alternative) tolifecycle.currentStateFlow.collectAsState()
.
See Collect lifecycle state with flows for more information.
Version 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
SavedStateHandle
would not properly restore customParcelable
classes 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
, andgetStateFlow
now specifically calls this limitation out. ( I0b55a )
Version 2.7.0-rc01
15 ноября 2023 г.
androidx.lifecycle:lifecycle-*:2.7.0-rc01
is released. Version 2.7.0-rc01 contains these commits.
Исправления ошибок
-
LifecycleStartEffect
andLifecycleResumeEffect
now correctly dispose and recreate the effect block if theLifecycleOwner
is changed. ( Ia25c6 )
Version 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.
Version 2.7.0-alpha03
18 октября 2023 г.
androidx.lifecycle:lifecycle-*:2.7.0-alpha03
is released. Version 2.7.0-alpha03 contains these commits.
Новые возможности
-
lifecycle-runtime-testing
now contains a new Lint check to avoid setting theLifecycle.State
of theTestLifecycleOwner
by using thecurrentState
field when inside of a coroutine. The Lint check now suggests the suspendingsetCurrentState
which allows setting theLifecycle.State
without blocking. ( Icf728 , b/297880630 )
Исправления ошибок
- Fixed an issue with
LiveData.switchMap
where returning the sameLiveData
instance both on the initial call and a subsequent call would prevent theLiveData
instance from being added as a source. ( Ibedcba7 )
Version 2.7.0-alpha02
6 сентября 2023 г.
androidx.lifecycle:lifecycle-*:2.7.0-alpha02
is released. Version 2.7.0-alpha02 contains these commits.
Новые возможности
-
TestLifecycleOwner
now includes the suspending functionsetCurrentState()
to give users the option of usingTestLifecycleOwner
from within a coroutine such as one provided byrunTest
. ( I329de , b/259344129 )
Изменения API
- All files from the
lifecycle-livedata-ktx
modules have been moved into the mainlifecycle-livedata
module. ( I10c6f , b/274800183 )
Изменения поведения
- The
LiveData.map()
andLiveData.switchMap()
extensions now sets thevalue
of the returnedLiveData
if the previousLiveData
has 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 theCloseable
if theViewModel
has already received a call toonCleared()
. ( I4712e , b/280294730 )
Исправления ошибок
- From Lifecycle
2.6.2
: Fixed an issue whereSavedStateHandle
would 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 betweenrememberSaveable
and Navigation Compose'sNavHost
. ( aosp/2729289 )
Version 2.7.0-alpha01
26 июля 2023 г.
androidx.lifecycle:lifecycle-*:2.7.0-alpha01
is released. Version 2.7.0-alpha01 contains these commits.
Изменения API
-
Lifecycle.State
is now Compose-observable viaLifecycle.currentStateFlow
, which returns aStateFlow
where thevalue
is the currentLifecycle.State
. ( Ib212d , b/209684871 ) -
Lifecycle.Event
s can now able to be observed as aFlow
withLifecycle.asFlow().
( If2c0f , b/176311030 ) -
LifecycleResumeEffect
API has been added to run ComposeSideEffect
s based on bothLifecycle.Event.ON_RESUME
andLifecycle.Event.ON_PAUSE
event callbacks. ( I60386 , b/235529345 ) -
LifecycleStartEffect
API has been added to run ComposeSideEffect
s based onLifecycle.Event.ON_START
andLifecycle.Event.ON_STOP
event callbacks. ( I5a8d1 , b/235529345 ) -
LifecycleEventEffect
API has been added to run ComposeSideEffect
s based onLifecycle.Event
. ( Ic9794 , b/235529345 ) -
Lifecycle.collectAsState()
extension has been added to directly exposeLifecycle.State
as ComposeState
. This is equivalent (and a shorter alternative) tolifecycle.currentStateFlow.collectAsState()
. ( I11015 , b/235529345 )
Исправления ошибок
- The
LiveData.distinctUntilChanged()
extension now sets thevalue
of the returnedLiveData
if the previousLiveData
has had a value set on it. This does not change the observation behavior - updated values from the sourceLiveData
will still only apply once you start observing theLiveData
returned fromdistinctUntilChanged()
. ( Ib482f ) - The proguard keep rules associated with
LifecycleObserver
have 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 )
Version 2.6
Version 2.6.2
6 сентября 2023 г.
androidx.lifecycle:lifecycle-*:2.6.2
is released. Version 2.6.2 contains these commits.
Исправления ошибок
- Fixed an issue where
SavedStateHandle
would 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 betweenrememberSaveable
and Navigation Compose'sNavHost
. ( aosp/2729289 )
Version 2.6.1
22 марта 2023 г.
androidx.lifecycle:lifecycle-*:2.6.1
is released. Version 2.6.1 contains these commits.
Обновления зависимостей
-
lifecycle-viewmodel-savedstate
now depends on SavedState1.2.1
. ( cd7251 ) - Lifecycle now depends on ProfileInstaller
1.3.0
. ( f9d30b )
Version 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
-
LiveData
now includes a newisInitialized
property that indicates whether an explicit value has ever been set on theLiveData
, allowing you to distinguish betweenliveData.value
returningnull
because no value has ever been set or an explicitnull
value. -
MediatorLiveData
now includes a constructor to set an initial value. - Added a new extension on
StateFlow
andFlow
ofcollectAsStateWithLifecycle()
that collect from flows and represents its latest value as Compose State in a lifecycle-aware manner. -
Lifecycle.launchWhenX
methods andLifecycle.whenX
methods 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
onChanged
method of aObserver
created in Kotlin now matches the nullability of the generic type. If you wantObserver.onChanged()
to accept a nullable type, you must instantiate theObserver
with 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
Version 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 thevalue
of the returnedLiveData
if the previousLiveData
has had a value set on it. This does not change the observation behavior - updated values from the sourceLiveData
will still only apply once you start observing theLiveData
returned fromdistinctUntilChanged()
. ( Ib482f )
Version 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
-
LifecycleOwner
is now written in Kotlin. This is a source incompatible change for classes written in Kotlin - they must now override thelifecycle
property rather than implementing the previousgetLifecycle()
function. ( I75b4b , b/240298691 ) -
ViewModelStoreOwner
is now in Kotlin. This is a source incompatible change for classes written in Kotlin - they must now override theviewModelStore
property rather than implementing the previousgetViewModelStore()
function. ( I86409 , b/240298691 ) - The Kotlin extension on
LifecycleOwner
that provides thelifecycleScope
field has been moved to thelifecycle-common
artifact fromlifecycle-runtime-ktx
. ( I41d78 , b/240298691 ) - The Kotlin extension on
Lifecycle
that provides thecoroutineScope
field has been moved to thelifecycle-common
artifact 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
-
Transformations
is 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.Function
method are deprecated and replaced with the versions that take a KotlinFunction1
. This change maintains binary compatibility. ( I8e14f ) -
ViewTreeViewModelStoreOwner
is 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 onView
ofandroidx.lifecycle.setViewTreeViewModelStoreOwner
andandroidx.lifecycle.findViewTreeViewModelStoreOwner
to 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
HasDefaultViewModelProviderFactory
interface is now written in Kotlin. This is a source incompatible change for classes written in Kotlin - they must now override thedefaultViewModelProviderFactory
anddefaultViewModelCreationExtras
properties rather than implementing the previous corresponding functions. ( Iaed9c , b/240298691 ) -
Observer
is now written in Kotlin. ItsonChanged()
method now uses the namevalue
for its parameter. ( Iffef2 , I4995e , b/240298691 ) -
AndroidViewModel
,AbstractSavedStateViewModelFactory
,LifecycleService
,ServiceLifecycleDispatcher
, andProcessLifecycleOwner
are 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.
Новые возможности
-
LiveData
now includes a newisInitialized
property that indicates whether an explicit value has ever been set on theLiveData
, allowing you to distinguish betweenliveData.value
returningnull
because no value has ever been set or an explicitnull
value. ( Ibd018 )
Изменения API
- The
collectAsStateWithLifecycle()
APIs oflifecycle-runtime-compose
are no longer in experimental status. ( I09d42 , b/258835424 ) -
Lifecycle.launchWhenX
methods andLifecycle.whenX
methods 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
-
ViewTreeLifecycleOwner
is 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 onView
ofandroidx.lifecycle.setViewTreeLifecycleOwner
andandroidx.lifecycle.findViewTreeLifecycleOwner
to 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 ) -
LiveDataReactiveStreams
is now written in Kotlin. The Kotlin extensions previously inlifecycle-reactivestreams-ktx
have been moved into thelifecycle-reactivestreams
module 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
, andViewModelStore
are now written in Kotlin ( Iadffd , ( I60034 , I8c52c , I9593d , I01fe1 , I59a23 , b/240298691 )
Исправления ошибок
-
SavedStateHandle
no longer crashes with aClassCastException
when callingget()
with the incorrect class type. ( I6ae7c )
Version 2.6.0-alpha03
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 )
Version 2.6.0-alpha02
7 сентября 2022 г.
androidx.lifecycle:lifecycle-*:2.6.0-alpha02
is released. Version 2.6.0-alpha02 contains these commits.
Изменения API
-
MediatorLiveData
now includes a constructor to set an initial value. ( Ib6cc5 , b/151244085 )
Исправления ошибок
-
Lifecycle
artifacts 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 acallbackFlow
rather than using its ownChannel
implementation to ensure thread-safety and context preservation. ( I4a8b2 , b/200596935 ) -
FlowLiveData
'sasLiveData
function will now preserve the initial value of aStateFlow
when creating the newLiveData
object. ( I3f530 , b/157380488 ) - From Lifecycle
2.5.1
: Custom implementations ofAndroidViewModelFactory
now correctly calls thecreate(modelClass)
function when using the stateful constructor withLifecycle
2.4+ ( I5b315 , b/238011621 )
Version 2.6.0-alpha01
29 июня 2022 г.
androidx.lifecycle:lifecycle-*:2.6.0-alpha01
is released. Version 2.6.0-alpha01 contains these commits.
Новые возможности
- Added a new extension on
StateFlow
andFlow
ofcollectAsStateWithLifecycle
that 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 )
Version 2.5
Version 2.5.1
27 июля 2022 г.
androidx.lifecycle:lifecycle-*:2.5.1
is released. Version 2.5.1 contains these commits.
Исправления ошибок
- Custom implementations of
AndroidViewModelFactory
now correctly call thecreate(modelClass)
function when using the statefulAndroidViewModelFactory
constructor withLifecycle
2.4+. ( I5b315 , b/238011621 )
Version 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
SavedStateHandle
now offers agetStateFlow()
API that returns a KotlinStateFlow
for monitoring value changes as an alternative to usingLiveData
.ViewModel CreationExtras - when writing a custom
ViewModelProvider.Factory
, it is no longer required to extendAndroidViewModelFactory
orAbstractSavedStateViewModelFactory
to gain access to anApplication
orSavedStateHandle
, respectively. Instead, these fields are provided to everyViewModelProvider.Factory
subclass asCreationExtras
via the new overload ofcreate
:create(Class<T>, CreationExtras)
. These extras are provided automatically by your Activity or Fragment when using Activity1.5.0
and 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-viewmodel
now provides aviewModelFactory
Kotlin DSL that allows you define yourViewModelProvider.Factory
in terms of one or more lambda initializers, one for each particularViewModel
class your custom factory supports, usingCreationExtras
as 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-compose
now offers aviewModel()
API that takes a lambda factory for creating aViewModel
instance 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-compose
artifact now contains new experimental APIs inSavedStateHandle.saveable
that allowrememberSaveable
like behavior backed by theSavedStateHandle
of 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 moreCloseable
objects to theViewModel
that will be closed when theViewModel
is 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
CoroutineScope
that 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
ViewModel
constructor 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 }
Behavior changes
- Attempting to move the
Lifecycle.State
fromINITIALIZED
toDESTROYED
will now always throw anIllegalStateException
regardless of whether theLifecycle
has an attached observer. -
LifecycleRegistry
will now clear their observers when they reach theDESTROYED
state.
Version 2.5.0-rc02
June 15, 2022
androidx.lifecycle:lifecycle-*:2.5.0-rc02
is released. Version 2.5.0-rc02 contains these commits.
Исправления ошибок
-
ViewModelProvider
will no longer crash when mixing previous versions of compileOnly Lifecycle dependencies with versions 2.5+. ( I81a66 , b/230454566 )
Version 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 aNullPointerException
when passed anull
source instead of propagating thenull
source to observers.( Ibd0fb , b/123085232 )
Version 2.5.0-beta01
April 20, 2022
androidx.lifecycle:lifecycle-*:2.5.0-beta01
is released. Version 2.5.0-beta01 contains these commits.
Изменения API
- Added
SavedStateHandle.saveable
property delegates to use property names as keys for persisting state into theSavedStateHandle
( I8bb86 , b/225014345 )
Исправления ошибок
- Fixed an issue where nesting one
NavHost
within anotherNavHost
in a non-primary bottom navigation tab would lead to anIllegalStateException
when 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
MutableState
overload toSavedStateHandle.saveable
for parity withrememberSaveable
( I38cfe , b/224565154 )
Изменения API
-
CreationExtras
is now abstract instead of sealed. ( Ib8a7a )
Исправления ошибок
- Fixed an
IllegalStateException: Already attached to lifecycleOwner
error 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-compose
module now providesSavedStateHandleSaver
, an experimental API that ensures values in aSavedStateHandle
are integrated correctly with the same saved instance state thatrememberSaveable
uses. ( Ia88b7 , b/195689777 )
Изменения API
- Fixed a compatibility issue with Lifecycle 2.3 and newer Lifecycle versions in Java. ( I52c8a , b/219545060 )
Исправления ошибок
-
SavedStateViewFactory
now supports usingCreationExtras
even 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
-
SavedStateHandle
now offers agetStateFlow()
API that returns a KotlinStateFlow
for monitoring value changes as an alternative to usingLiveData
. ( Iad3ab , b/178037961 )
Version 2.5.0-alpha03
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 moreCloseable
objects to theViewModel
that will be closed when theViewModel
is cleared without requiring any manual work inonCleared()
. ( I55ea0 ) -
lifecycle-viewmodel
now provides anInitializerViewModelFactory
that allows you to add lambda for handling particularViewModel
classes, usingCreationExtras
as the primary data source. ( If58fc , b/216687549 ) -
lifecycle-viewmodel-compose
now offers aviewModel()
API that takes a lambda factory for creating aViewModel
instance without requiring the creation of a customViewModelProvider.Factory
. ( I97fbb , b/216688927 )
Изменения API
- You can now create a
ViewModel
withCreationExtras
vialifecycle-viewmodel-compose
. ( I08887 , b/216688927 )
Behavior changes
- Attempting to move the
Lifecycle.State
fromINITIALIZED
toDESTROYED
will now always throw anIllegalStateException
regardless of whether theLifecycle
has an attached observer. ( I7c390 , b/177924329 ) -
LifecycleRegistry
will now clear their observers when they reach theDESTROYED
state. ( I4f8dd , b/142925860 )
Version 2.5.0-alpha02
9 февраля 2022 г.
androidx.lifecycle:lifecycle-*:2.5.0-alpha02
is released. Version 2.5.0-alpha02 contains these commits.
Изменения API
-
SavedStateHandle
andSavedStateViewModelFactory
have been converted to Kotlin. This has improved the nullability of the generics in both classes. ( Ib6ce2 , b/216168263 , I9647a , b/177667711 ) - The
LiveData
switchMap
function parameter can now have a nullable output. ( I40396 , b/132923666 ) - The
LiveData
-ktx extensions are now annotated with@CheckResult
to enforce that the result is used when calling these functions. ( Ia0f05 , b/207325134 )
Behavior changes
-
SavedStateHandle
now properly stores the defaultValue when no value for the specified key exists. ( I1c6ce , b/178510877 )
Исправления ошибок
- From Lifecycle
2.4.1
: Updatedlifecycle-process
to depend on Startup 1.1.1 to ensure that fixes that preventProcessLifecycleInitializer
from throwing aStartupException
are available by default. ( Ib01df , b/216490724 ) - There is now an improved error message when custom
AndroidViewModel
classes have parameters in the wrong order and attempt to create aViewModel
. ( I340f7 , b/177667711 ) - You can now create a view model via
CreationExtras
using theAndroidViewModelFactory
without setting an application. ( I6ebef , b/217271656 )
Version 2.5.0-alpha01
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
: thisString
provides access to the custom key you passed toViewModelProvider.get()
. -
ViewModelProvider.AndroidViewModelFactory.APPLICATION_KEY
provides access to theApplication
class. -
SavedStateHandleSupport.SAVED_STATE_REGISTRY_OWNER_KEY
provides access to theSavedStateRegistryOwner
that is being used to construct this ViewModel. -
SavedStateHandleSupport.VIEW_MODEL_STORE_OWNER_KEY
provides access to theViewModelStoreOwner
that is being used to construct this ViewModel. -
SavedStateHandleSupport.DEFAULT_ARGS_KEY
provides access to theBundle
of 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 идем вперед.
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
SavedStateHandle
would reappear after process death and recreation, even if it was specifically removed from theSavedStateHandle
. As a consequence of this,SavedStateHandle
will no longer merge default values and restored values together, instead only using the restored values as the source of truth. ( I53a4b )
Version 2.4
Version 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 aSavedStateHandle
would re-appear after process death and recreation, even if it was specifically removed from theSavedStateHandle
. As a consequence of this,SavedStateHandle
will no longer merge default values and restored values together, instead only using the restored values as the source of truth. ( I53a4b ) -
lifecycle-process
now depends on Androidx Startup 1.1.1 which fixed a regression in where usingProcessLifecycleInitializer
would cause anStartupException
. ( b/216490724 )
Version 2.4.0
27 октября 2021 г.
androidx.lifecycle:lifecycle-*:2.4.0
is released. Version 2.4.0 contains these commits.
Important changes since 2.3.0
-
@OnLifecycleEvent
was deprecated.LifecycleEventObserver
orDefaultLifecycleObserver
should be used instead. -
androidx.lifecycle:lifecycle-viewmodel-compose
library was added. It providesviewModel()
composable andLocalViewModelStoreOwner
.- Source-breaking change :
ViewModelProvider
has been rewritten in Kotlin.ViewModelProvider.Factory.create
method 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. -
DefaultLifecycleObserver
was moved fromlifecycle.lifecycle-common-java8
tolifecycle.lifecycle-common
.lifecycle.lifecycle-common-java8
doesn'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-ktx
have been moved to thelifecycle-viewmodel
module. lifecycle-process
now usesandroidx.startup
to initialize theProcessLifecycleOwner
.Previously, this was being done by
androidx.lifecycle.ProcessLifecycleOwnerInitializer
.If you used
tools:node="remove"
theContentProvider
being 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>
Version 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.
Version 2.4.0-beta01
September 15, 2021
androidx.lifecycle:lifecycle-*:2.4.0-beta01
is released. Version 2.4.0-beta01 contains these commits.
Изменения API
-
@OnLifecycleEvent
was deprecated.LifecycleEventObserver
orDefaultLifecycleObserver
should be used instead. ( I5a8fa ) - DefaultLifecycleObserver was moved from
androidx.lifecycle.lifecycle-common-java8
toandroidx.lifecycle.lifecycle-common
.androidx.lifecycle.lifecycle-common-java8
doesn'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-ktx
have been moved to thelifecycle-viewmodel
module. ( I6d5b2 )
Внешний вклад
Version 2.4.0-alpha03
August 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.create
method no longer allows nullable generic. ( I9b9f6 )
Изменения поведения
- The
Lifecycle.repeatOnLifecycle
:block
is now always invoked serially when repeating execution. ( Ibab33 )
Внешний вклад
- Thanks chao2zhang for fixing the code snippets in the
repeatOnLifecycle
documentation. #205 .
Version 2.4.0-alpha02
16 июня 2021 г.
androidx.lifecycle:lifecycle-*:2.4.0-alpha02
is released. Version 2.4.0-alpha02 contains these commits.
Новые возможности
- Added a new
RepeatOnLifecycleWrongUsage
lint check tolifecycle-runtime-ktx
that detects whenrepeateOnLifecycle
is incorrectly used inonStart()
oronResume()
. ( 706078 , b/187887400 )
Изменения API
- The
LifecycleOwner.addRepeatingJob
API is removed in favor ofLifecycle.repeatOnLifecycle
that respects structured concurrency and is easier to reason about. ( I4a3a8 ) - Make
ProcessLifecycleInitializer
public so otherandroidx.startup.Initializer
s can use these as dependencies. ( I94c31 )
Исправления ошибок
- Fixed an issue with the
NullSafeMutableLiveData
lint check when the field has modifiers. ( #147 , b/183696616 ) - Fixed another issue with the
NullSafeMutableLiveData
lint check when using generics. ( #161 , b/184830263 )
Внешний вклад
- Thanks maxsav for improving the
NullSafeMutableLiveData
lint check. ( #147 , b/183696616 ) - Thanks kozaxinan for improving the
NullSafeMutableLiveData
lint check. ( #161 , b/184830263 )
Version 2.4.0-alpha01
24 марта 2021 г.
androidx.lifecycle:lifecycle-*:2.4.0-alpha01
is released. Version 2.4.0-alpha01 contains these commits.
Изменения поведения
lifecycle-process
now usesandroidx.startup
to initialize theProcessLifecycleOwner
.Previously, this was being done by
androidx.lifecycle.ProcessLifecycleOwnerInitializer
.If you used
tools:node="remove"
theContentProvider
being 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.flowWithLifecycle
API that emits values from the upstream Flow when the lifecycle is at least in a certain state using theLifecycle.repeatOnLifecycle
API. This is an alternative to the also newLifecycleOwner.addRepeatinJob
API. ( I0f4cd )
Исправления ошибок
- From Lifecycle 2.3.1 : The
NonNullableMutableLiveData
lint 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.
Breaking API Changes
-
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
June 2, 2021
androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha06
is released. Версия 1.0.0-alpha06 содержит эти коммиты.
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. Версия 1.0.0-alpha05 содержит эти коммиты.
Новые возможности
- 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
April 7, 2021
androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha04
is released. Версия 1.0.0-alpha04 содержит эти коммиты.
Dependency Changes
- This version allows
androidx.hilt:hilt-navigation-compose
andandroidx.navigation:navigation-compose
to sync dependencies onandroidx.compose.compiler:compiler:1.0.0-beta04
andandroidx.compose.runtime:runtime:1.0.0-beta04
. For 1.0.0, it is required that the compiler and runtime match.
Версия 1.0.0-альфа03
March 10, 2021
androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha03
is released. Версия 1.0.0-alpha03 содержит эти коммиты.
Изменения API
-
LocalViewModelStoreOwner.current
now returns a nullableViewModelStoreOwner
to better determine whether aViewModelStoreOwner
is available in the current composition. APIs that require aViewModelStoreOwner
, such asviewModel()
andNavHost
, still throw an exception if aViewModelStoreOwner
is not set. ( Idf39a )
Lifecycle-Viewmodel-Compose Version 1.0.0-alpha02
24 февраля 2021 г.
androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha02
is released. Версия 1.0.0-alpha02 содержит эти коммиты.
Изменения API
-
LocalViewModelStoreOwner
now has aprovides
functions 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. Версия 1.0.0-alpha01 содержит эти коммиты.
Новые возможности
- The
viewModel()
composable andLocalViewModelStoreOwner
were moved fromandroidx.compose.ui.viewinterop
to this artifact in theandroidx.lifecycle.viewmodel.compose
package. ( I7a374 )
Version 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
NonNullableMutableLiveData
lint rule can now properly differentiate between field variables with different nullability. ( b/169249668 )
Version 2.3.0
Version 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
-
SavedStateHandle
support for non-parcelable classes :SavedStateHandle
now supports lazy serialization by allowing you to callsetSavedStateProvider()
for a given key, providing aSavedStateProvider
that will get a callback tosaveState()
when theSavedStateHandle
is asked to save its state. See Saving non-parcelable classes . - Lifecycle Behavior Enforcement :
- LifecycleRegistry now enforces
DESTROYED
as a terminal state. -
LifecycleRegistry
now 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. ForLifecycleRegistry
objects 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 thisLifecycleRegistry
is 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.Event
for generating theEvent
given aState
and transition direction. Added thegetTargetState()
method that provides theState
that the Lifecycle will transition to directly following theEvent
. -
withStateAtLeast
: AddedLifecycle.withStateAtLeast
APIs 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 ) -
ViewTree
APIs : A newViewTreeLifecycleOwner.get(View)
andViewTreeViewModelStoreOwner.get(View)
API allows you to retrieve the containingLifecycleOwner
andViewModelStoreOwner
, respectively, given aView
instance. You must upgrade to Activity1.2.0
and Fragment1.3.0
, and AppCompat 1.3.0-alpha01 or higher to populate this correctly. ThefindViewTreeLifecycleOwner
andfindViewTreeViewModelStoreOwner
Kotlin extensions are available inlifecycle-runtime-ktx
andlifecycle-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.
Version 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 ofSavedStateHandle
is 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 )
Version 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 )
Documentation Changes
- The
liveData
builder 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
NullSafeMutableLiveData
Lint 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.Event
for generating theEvent
given aState
and transition direction. Added thegetTargetState()
method that provides theState
that the Lifecycle will transition to directly following theEvent
. ( I00887 ) - Added
Lifecycle.withStateAtLeast
APIs 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
DESTROYED
as a terminal state. ( I00887 ) -
LifecycleRegistry
now 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. ForLifecycleRegistry
objects 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 thisLifecycleRegistry
is accessed from different threads ( Ie7280 , b/137392809 )
Исправления ошибок
- Fixed a crash in
NullSafeMutableLiveData
. ( b/159987480 ) - Fixed an
ObsoleteLintCustomCheck
for 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.
Исправления ошибок
-
LiveData
now 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 )
Version 2.3.0-alpha04
10 июня 2020 г.
androidx.lifecycle:lifecycle-*:2.3.0-alpha04
is released. Version 2.3.0-alpha04 contains these commits.
Исправления ошибок
- Fixed a crash in the
NonNullableMutableLiveData
Lint check. ( b/157294666 ) - The
NonNullableMutableLiveData
Lint check now covers significantly more cases where anull
value was set on aMutableLiveData
with a non-null type parameter. ( b/156002218 )
Version 2.3.0-alpha03
May 20, 2020
androidx.lifecycle:lifecycle-*:2.3.0-alpha03
are released. Version 2.3.0-alpha03 contains these commits.
Новые возможности
-
SavedStateHandle
now supports lazy serialization by allowing you to callsetSavedStateProvider()
for a given key, providing aSavedStateProvider
that will get a callback tosaveState()
when theSavedStateHandle
is asked to save its state. ( b/155106862 ) - A new
ViewTreeViewModelStoreOwner.get(View)
API allows you to retrieve the containingViewModelStoreOwner
given aView
instance. You must upgrade to Activity1.2.0-alpha05
, Fragment1.3.0-alpha05
, and AppCompat1.3.0-alpha01
to populate this correctly. AfindViewModelStoreOwner()
Kotlin extension has been added tolifecycle-viewmodel-ktx
. ( aosp/1295522 )
Исправления ошибок
- Fixed an issue that caused the
MutableLiveData
Lint checks released in Lifecycle2.3.0-alpha01
from being published alongside thelifecycle-livedata-core-ktx
artifact. ( b/155323109 )
Version 2.3.0-alpha02
29 апреля 2020 г.
androidx.lifecycle:lifecycle-*:2.3.0-alpha02
is released. Version 2.3.0-alpha02 contains these commits.
Изменения API
-
SavedStateViewModelFactory
now allows you to pass a nullApplication
to its constructor to better support cases where one is not readily available and support forAndroidViewModel
is not needed. ( aosp/1285740 )
Исправления ошибок
- Improved cold start performance by avoiding class verification failure on API 28 and lower devices. ( aosp/1282118 )
Version 2.3.0-alpha01
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 containingLifecycleOwner
given aView
instance. You must upgrade to Activity1.2.0-alpha01
and Fragment1.3.0-alpha01
to populate this correctly. AfindViewTreeLifecycleOwner
Kotlin extension is available inlifecycle-runtime-ktx
. ( aosp/1182361 , aosp/1182956 ) - Added a new Lint check that warns you when setting a
null
value on aMutableLiveData
that has been defined in Kotlin as non-null. This is available when using thelivedata-core-ktx
orlivedata-ktx
artifacts. ( aosp/1154723 , aosp/1159092 ) - A new
lifecycle-runtime-testing
artifact is available that provides aTestLifecycleOwner
that implementsLifecycleOwner
and provides a thread safe mutableLifecycle
. ( aosp/1242438 )
Исправления ошибок
- The
lifecycle-runtime
artifact now has a unique package name. ( aosp/1187196 )
Version 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
.
Version 2.2.0
January 22, 2020
androidx.lifecycle:lifecycle-*:2.2.0
is released. Version 2.2.0 contains these commits .
Important changes since 2.1.0
- Lifecycle Coroutine Integration : The new
lifecycle-runtime-ktx
artifact adds integration between Lifecycle and Kotlin coroutines. Thelifecycle-livedata-ktx
has 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 aFragment
orFragmentActivity
to the newViewModelProvider(ViewModelStoreOwner)
constructor to achieve the same functionality when using Fragment1.2.0
. -
lifecycle-extensions
Artifact Deprecation : With the above deprecation ofViewModelProviders.of()
, this release marks the deprecation of the last API inlifecycle-extensions
and this artifact should now be considered deprecated in its entirety. We strongly recommend depending on the specific Lifecycle artifacts you need (such aslifecycle-service
if you're usingLifecycleService
andlifecycle-process
if you're usingProcessLifecycleOwner
) rather thanlifecycle-extensions
as there will not be a future2.3.0
release 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
DefautLifecycleObserver
instead; 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
ViewModel
was stored inViewModelStore
and queried later with default factory. - Fix a usage of
Dispatchers.Main.immediate
inlaunchWhenCreated
and similar methods to be called synchronously during corresponding lifecycle event. ( aosp/1156203 )
External contributions
- 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 )
Version 2.2.0-rc01
October 23, 2019
androidx.lifecycle:lifecycle-*:2.2.0-rc01
is released. Version 2.2.0-rc01 contains these commits .
Исправления ошибок
- Fixed an issue where
launchWhenCreated
and related methods would run one frame later than the associated lifecycle method due to its use ofDispatchers.Main
instead ofDispatchers.Main.immediate
. ( aosp/1145596 )
External contributions
- Thanks to Nicklas Ansman for contributing the fix! ( aosp/1145596 )
Version 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
ProcessLifecycleOwner
and the activity'sLifecycleOwner
moving to started and resumed on Android 10 devices. ( aosp/1128132 ) - Fixed a regression introduced in Lifecycle
2.2.0-alpha05
which would cause aNullPointerException
when using version2.0.0
or2.1.0
oflifecycle-process
. ( b/141536990 )
Version 2.2.0-alpha05
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 ofliveData
now useDispatchers.Main.immediate
instead ofDispatchers.Main
. ( b/139740492 )
External contributions
- 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
ViewModelStoreOwner
can now optionally implementHasDefaultViewModelProviderFactory
to 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 aFragment
orFragmentActivity
to the newViewModelProvider(ViewModelStoreOwner)
constructor to achieve the same functionality. ( aosp/1009889 )
Version 2.2.0-alpha02
2 июля 2019 г.
androidx.lifecycle:*:2.2.0-alpha02
is released. The commits included in this version can be found here .
Изменения API
- Replaced
LiveDataScope.initialValue
withLiveDataScope.latestValue
which will track the current emitted value of theliveData
block. - Added a new overload to the
liveData
builder that receivestimeout
parameter as typeDuration
Version 2.2.0-alpha01
May 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
Version 1.0.0
January 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
ViewModel
classes to access and to contribute to the saved state. This object can be received in constructor ofViewModel
class and factories provided by default by Fragments and AppCompatActivity will injectSavedStateHandle
automatically. - AbstractSavedStateViewModelFactory was added. It allows you to create custom factories for your
ViewModel
and 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
October 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
IllegalStateException
when usingAbstractSavedStateViewModelFactory
. ( b/141225984 )
ViewModel-SavedState Version 1.0.0-alpha05
18 сентября 2019 г.
androidx.lifecycle:lifecycle-viewmodel-savedstate:1.0.0-alpha05
is released. Версия 1.0.0-alpha05 содержит эти коммиты .
Изменения API
-
SavedStateViewModelFactory
no longer extendsAbstractSavedStateViewModelFactory
andSavedStateHandle
is 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-savedstate
no longer depends onfragment
and the relatedSavedStateViewModelFactory(Fragment)
andSavedStateViewModelFactory(FragmentActivity)
constructors have been removed. Instead,SavedStateViewModelFactory
is 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
-
SavedStateVMFactory
is renamed toSavedStateViewModelFactory
. -
AbstractSavedStateVMFactory
is 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
ViewModels
can contribute to savedstate. To do that you use newly introduced viewmodel's factorySavedStateVMFactory
and your ViewModel should have a constructor that receivesSavedStateHandle
object as a parameter.
Version 2.1.0
Important changes since 2.0.0
- Added
LifecycleEventObserver
for the cases when a stream of lifecycle events is needed. It is a public API instead of a hiddenGenericLifecycleObserver
class. - Added ktx extensions for
LiveData.observe
methods andTransformations.*
methods. - Added
Transformations.distinctUntilChanged
, which creates a new LiveData object that does not emit a value until the sourceLiveData
value has been changed. - Added coroutine support in ViewModels by adding the extension property
ViewModel.viewModelScope
.
Version 2.1.0
5 сентября 2019 г.
androidx.lifecycle:lifecycle-*:2.1.0
is released. The commits included in this version can be found here .
Version 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 .
Version 2.1.0-beta01
May 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
liveData
extension functions for transformations and observations,ViewModel
initialisation with property delegation and others are stabilised and not going to change.
Version 2.1.0-alpha04
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 aViewModelStore
directly, rather than only aViewModelStoreOwner
. ( aosp/932932 )
Version 2.1.0-alpha03
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.KeyedFactory
was removed. Second interface in addition toViewModelProvider.Factory
didn't compose well with new features as property delegation in Kotlinby viewmodels {}
. ( aosp/914133 )
Version 2.1.0-alpha02
January 30, 2019
androidx.lifecycle 2.1.0-alpha02
is released.
Изменения API
-
LifecycleRegistry
now contains asetCurrentState()
method that replaces the now deprecatedsetState()
method. ( aosp/880715 )
Исправления ошибок
- Fixed an issue where mock
ViewModel
instances would crash when the containingViewModelStore
was cleared. b/122273087
Version 2.1.0-alpha01
December 17, 2018
androidx.lifecycle 2.1.0-alpha01
is released.
Новые возможности
- Added
LifecycleEventObserver
for the cases when a stream of lifecycle events is needed. It is a public api instead of a hiddenGenericLifecycleObserver
class. - Added ktx extensions for
LiveData.observe
methods andTransformations.*
methods. - Method
Transformations.distinctUntilChanged
was added. It creates a newLiveData
object that does not emit a value until the source LiveData value has been changed. - Coroutine support in ViewModels: extension property
ViewModel.viewModelScope
was added. - Added
ViewModelProvider.KeyedFactory
, a factory for ViewModels that receiveskey
andClass
increate
method.
Version 2.0.0
Version 2.0.0
September 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
Version 2.0.0-beta01
July 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
March 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 г.
Packaging Changes
New, much smaller dependencies are now available:
-
android.arch.lifecycle:livedata:1.1.0
-
android.arch.lifecycle:viewmodel:1.1.0
Изменения API
- The deprecated
LifecycleActivity
andLifecycleFragment
have now been removed - please useFragmentActivity
,AppCompatActivity
or supportFragment
. -
@NonNull
annotations have been added toViewModelProviders
andViewModelStores
-
ViewModelProviders
constructor has been deprecated - please use its static methods directly -
ViewModelProviders.DefaultFactory
has been deprecated - please useViewModelProvider.AndroidViewModelFactory
- The static
ViewModelProvider.AndroidViewModelFactory.getInstance(Application)
method has been added to retrieve a staticFactory
suitable for creatingViewModel
andAndroidViewModel
instances.
Жизненный цикл
This table lists all the artifacts in the androidx.lifecycle
group.
Артефакт | Стабильный выпуск | Кандидат на выпуск | Бета-версия | Альфа-релиз |
---|---|---|---|---|
жизненный цикл-* | 2.8.6 | - | - | 2.9.0-alpha03 |
lifecycle-viewmodel-compose | 2.8.6 | - | - | 2.9.0-alpha03 |
Объявление зависимостей
To add a dependency on Lifecycle, you must add the Google Maven repository to your project. Для получения дополнительной информации прочтите репозиторий Google Maven .
Добавьте зависимости для нужных вам артефактов в файл build.gradle
для вашего приложения или модуля:
Котлин
классный
dependencies { def lifecycle_version = "2.8.7" 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" // 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.8.7" 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") // 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.8.7" 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.8.7" 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") }
For more information about dependencies, see Add Build Dependencies .
Обратная связь
Ваши отзывы помогают сделать Jetpack лучше. Дайте нам знать, если вы обнаружите новые проблемы или у вас есть идеи по улучшению этой библиотеки. Пожалуйста, ознакомьтесь с существующими проблемами в этой библиотеке, прежде чем создавать новую. Вы можете добавить свой голос к существующей проблеме, нажав кнопку со звездочкой.
Дополнительную информацию см . в документации по системе отслеживания проблем .
Version 2.9
Version 2.9.0-alpha03
18 сентября 2024 г.
androidx.lifecycle:lifecycle-*:2.9.0-alpha03
is released. Version 2.9.0-alpha03 contains these commits .
Исправления ошибок
- From Lifecycle
2.8.6
: TheNullSafeMutableLiveData
Lint error has improved support for smart casts, avoiding false positives. ( 85fed6 , b/181042665 )
Обновления зависимостей
- From Lifecycle
2.8.6
: Lifecycle Runtime Compose now depends on Compose Runtime1.7.1
- Lifecycle Runtime now depends on ProfileInstaller
1.4.0
Version 2.9.0-alpha02
4 сентября 2024 г.
androidx.lifecycle:lifecycle-*:2.9.0-alpha02
is released. Version 2.9.0-alpha02 contains these commits .
Исправления ошибок
- From Lifecycle
2.8.5
: Update theandroidx.lifecycle.ReportFragment
ProGuard rules to allow obfuscation . ( ff898e1 )
Внешний вклад
- Move
androidx.compose.ui.platform.LocalLifecycleOwner
to common source set (KMP). Thanks Ivan Matkov from JetBrains for the contribution. ( 8cd5d03 ) - From Lifecycle
2.8.5
: SavedStateHandle.saveable` extension delegate now supports nullable values. Thanks Roman Kalukiewicz for the contribution. ( 0d78ea6 )
Version 2.9.0-alpha01
7 августа 2024 г.
androidx.lifecycle:lifecycle-*:2.9.0-alpha01
is released. Version 2.9.0-alpha01 contains these commits .
Kotlin Multiplatform
-
lifecycle-testing
is now KMP compatible. ( Iea41e ) - Add support for
linuxArm64
kotlin multiplatform target ( I139d3 , b/338268719 )
Новые возможности
- A new
androidx.lifecycle:lifecycle-viewmodel-testing
KMP artifact is available that provides aViewModelScenario
class for testing ViewModels in isolation, with support foronCleared
(all platforms) andSavedStateHandle
(Android only). ( 337f68d , c9b3409 , 9799a95c , b/264602919 ) - Creating a
ViewModel
withViewModelProvider
is now thread safe;@MainThread
annotations have been removed. ( Ifd978 , b/237006831 )
Изменения API
- Add the
CreationExtras.Key()
factory function to simplify the creation of anonymousCreationExtras.Key
objects. ( I970ee ) -
CreationExtras
now includes map-like operator overloads to enable idiomatic manipulation of content in Kotlin. It allows the use ofin
,+=
, and+
withCreationExtras
. ( Ib4353 ) -
CreationExtras
now implementsequals
,hashCode
, andtoString
methods. ( Ib4353 ) -
NewInstanceFactory
is now available on JVM Desktop and Android targets. ( d3d0892 ) - Inline extension property to expose underlying Application safely in Kotlin language version 2.0 ( I39df2 )
Исправления ошибок
- Removed manual outlining of access to new platform APIs since this happens automatically via API modeling when using R8 with AGP 7.3 or later (eg R8 version 3.3) and for all builds when using AGP 8.1 or later (eg D8 version 8.1). Clients who are not using AGP are advised to update to D8 version 8.1 or later. See this article for more details. ( If6b4c , b/345472586 )
Version 2.8
Version 2.8.6
18 сентября 2024 г.
androidx.lifecycle:lifecycle-*:2.8.6
is released. Version 2.8.6 contains these commits .
Исправления ошибок
- The
NullSafeMutableLiveData
Lint error has improved support for smart casts, avoiding false positives. ( 85fed6 , b/181042665 )
Обновления зависимостей
- Lifecycle Runtime Compose now depends on Compose Runtime
1.7.1
Version 2.8.5
4 сентября 2024 г.
androidx.lifecycle:lifecycle-*:2.8.5
is released. Version 2.8.5 contains these commits .
Исправления ошибок
- Update the
androidx.lifecycle.ReportFragment
ProGuard rules to allow obfuscation . ( ff898e1 )
Внешний вклад
-
SavedStateHandle.saveable
extension delegate now supports nullable values. Thanks Roman Kalukiewicz for the contribution. ( 0d78ea6 )
Version 2.8.4
24 июля 2024 г.
androidx.lifecycle:lifecycle-*:2.8.4
is released. Version 2.8.4 contains these commits .
Исправления ошибок
-
LiveData.asFlow()
now correctly handles cases where the returned Flow is immediately completed after receiving a value already set on theLiveData
(for example, when usingtake(1)
). ( I9c566 ) -
Lifecycle*Effect
completion is now idempotent (ie, if theonStopOrDispose
was called because of the Lifecycle being stopped, it won't be called a second time upon disposal unless the Lifecycle goes back up toSTARTED
again). ( I5f607 , b/352364595 )
Version 2.8.3
1 июля 2024 г.
androidx.lifecycle:lifecycle-*:2.8.3
is released. Version 2.8.3 contains these commits .
Исправления ошибок
- Fixed an issue with Lifecycle 2.8's backward compatibility with Compose 1.6.0 and lower when using code shrinking. ( aosp/3133056 , b/346808608 )
Version 2.8.2
12 июня 2024 г.
androidx.lifecycle:lifecycle-*:2.8.2
is released. Version 2.8.2 contains these commits .
Исправления ошибок
- Fixed
CompositionLocal LocalLifecycleOwner not present
errors when using Lifecycle 2.8.X with Compose 1.6.X or earlier - you can now use Lifecycle 2.8.2 with any version of Compose without any workarounds required. ( aosp/3105647 , b/336842920 ) -
ViewModelProvider
will no longer crash when mixing previous versions ofcompileOnly
Lifecycle dependencies with versions 2.8+, fixing issues with libraries such as LeakCanary. ( I80383 , b/341792251 )
Version 2.8.1
29 мая 2024 г.
androidx.lifecycle:lifecycle-*:2.8.1
is released. Version 2.8.1 contains these commits .
Исправления ошибок
-
lifecycle-viewmodel-compose
now only has a common dependency oncompose-runtime
, removing its common dependency oncompose-ui
. The Android artifact retains itscompose-ui
for compatibility. ( aosp/3079334 , b/339562627 ) -
ViewModel
'ssaveable
integration using property delegates now uses the class name as part of the auto-generated key, avoiding conflicts if multiple classes use the sameSavedStateHandle
. ( aosp/3063463 )
Version 2.8.0
14 мая 2024 г.
androidx.lifecycle:lifecycle-*:2.8.0
is released. Version 2.8.0 contains these commits .
Important changes since 2.7.0
-
LocalLifecycleOwner
has been moved from Compose UI tolifecycle-runtime-compose
so that its Compose-based helper APIs can be used outside of Compose UI. - The
lifecycle-runtime-compose
artifact now contains thedropUnlessResumed
anddropUnlessStarted
APIs which allow you to drop click or other events that occur even after theLifecycleOwner
has dropped below the givenLifecycle.State
. For example, this can be used with Navigation Compose to avoid handling click events after a transition to another screen has already begun:onClick: () -> Unit = dropUnlessResumed { navController.navigate(NEW_SCREEN) }
ViewModel.viewModelScope
is now an overridable constructor parameter, allowing you to inject your own dispatcher andSupervisorJob()
or to override the default by using thebackgroundScope
available withinrunTest
. ( 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
has been rewritten in Kotlin and now usesAutoClosable
instead ofCloseable
. It now supports addingAutoCloseable
objects with akey
that allows retrieving them viagetCloseable()
.Calling
LifecycleStartEffect
andLifecycleResumeEffect
without a key is now an error, following the same convention as theDisposableEffect
API that these APIs mirror.Deprecated
LiveDataReactiveStreams.toPublisher(lifecycleOwner, liveData)
in favor ofLiveData.toPublisher(lifecycleOwner)
.The
lifecycle-livedata-core-ktx
kotlin extensions have now been moved to thelifecycle-livedata-core
module.The
NullSafeMutableLiveData
has been refactored to avoid many false positives.
Lifecycle Kotlin Multiplatform Compatibility
The core Lifecycle APIs in Lifecycle
, LifecycleOwner
, LifecycleObserver
, Lifecycle.State
, Lifecycle.Event
, and LifecycleRegistry
are now shipped in artifacts compatible with Kotlin Multiplatform.
Artifacts impacted:
-
lifecycle-common
moves most APIs tocommon
and supports jvm and iOS in addition to Android. -
lifecycle-runtime
moves most APIs tocommon
and supports jvm and iOS in addition to Android. -
lifecycle-runtime-ktx
is now empty, with all APIs being moved intolifecycle-runtime
. -
lifecycle-runtime-compose
moves all APIs tocommon
and ships an Android artifact, matching the multiplatform support ofandroidx.compose
.
ViewModel Kotlin Multiplatform Compatibility
The lifecycle-viewmodel
artifact and APIs like ViewModel
, ViewModelStore
, ViewModelStoreOwner
, and ViewModelProvider
are now shipped in artifacts compatible with Kotlin Multiplatform.
To accommodate this change, methods such as those on ViewModelProvider
that took a java.lang.Class<T>
now have an equivalent method that takes a kotlin.reflect.KClass<T>
.
Binary compatibility on Android has been maintained, but there are a few notable changes when comparing the Android API surface to the common API surface:
- Constructing a
ViewModelProvider
instance is now done through theViewModelProvider.create()
methods rather than directly calling its constructor. -
ViewModelProvider.NewInstanceFactory
andViewModelProvider.AndroidViewModelFactory
are only available on Android.- Custom Factories are recommended to extend from
ViewModelProvider.Factory
and use thecreate
method that takes aCreationExtras
or use theviewModelFactory
Kotlin DSL.
- Custom Factories are recommended to extend from
- Using
ViewModelProvider
without a custom factory on non-JVM platforms will result in anUnsupportedOperationException
. On JVM platforms, compatibility is preserved by using the no-args ViewModel constructor if a custom factory is not provided. -
viewModelScope
will fallback to anEmptyCoroutineContext
in platforms whereDispatchers.Main
is not available (eg, Linux).
Artifacts impacted:
-
lifecycle-viewmodel
moves most APIs tocommon
and supports jvm and iOS in addition to Android. -
lifecycle-viewmodel-ktx
is now empty, with all APIs being moved intolifecycle-viewmodel
. -
lifecycle-viewmodel-compose
moves all APIs tocommon
and ships an Android artifact, matching the multiplatform support ofandroidx.compose
.
Изменения поведения
-
InitializerViewModelFactory
(includingviewModelFactory
builder function) will now throw anIllegalArgumentException
if ainitializer
with the sameclazz: KClass<VM : ViewModel>
has already been added. ( Ic3a36 )
Известные проблемы
-
lifecycle-*:2.8.0
requires a minimum Compose version of 1.7.0-alpha05 ( b/336842920 ).
Version 2.8.0-rc01
1 мая 2024 г.
androidx.lifecycle:lifecycle-*:2.8.0-rc01
is released. Version 2.8.0-rc01 contains these commits .
Исправления ошибок
- Fixed an issue where the Baseline Profile for
lifecycle-common
classes was not properly packaged. These are now packaged in thelifecycle-runtime
AAR. ( aosp/3038274 , b/322382422 ) - Fixed an unintentional ordering change in how
AutoCloseable
instances attached to a ViewModel are cleared - the previous order ofaddCloseable(String, AutoCloseable)
, thenaddClosable(AutoCloseable)
, thenonCleared()
has been restored. ( aosp/3041632 ) - Improve the default creation behavior for
viewModelScope
for native and JVM Desktop environments. ( aosp/3039221 )
Внешний вклад
- Thanks Victor Kropp for improving the checking for the main thread on JVM Desktop. ( aosp/3037116 )
Version 2.8.0-beta01
17 апреля 2024 г.
androidx.lifecycle:lifecycle-*:2.8.0-beta01
is released. Version 2.8.0-beta01 contains these commits .
Новые возможности
- The
lifecycle-runtime-compose
artifact is now compatible with Kotlin Multiplatform, moving its code tocommon
and ships an Android artifact, matching the multiplatform support forandroidx.compose
. ( If7a71 , I4f4a0 , b/331769623 )
Version 2.8.0-alpha04
3 апреля 2024 г.
androidx.lifecycle:lifecycle-*:2.8.0-alpha04
is released. Version 2.8.0-alpha04 contains these commits .
Новые возможности
- The
lifecycle-viewmodel-compose
artifact is now compatible with Kotlin Multiplatform, moving its code tocommon
and ships an Android artifact, matching the multiplatform support ofandroidx.compose
. The accommodate this change, the ComposableviewModel
method now accepts aKClass
in addition to ajava.lang.Class
. ( b/330323282 )
Исправления ошибок
- The
NullSafeMutableLiveData
has been refactored to avoid many false positives. ( I2d8c1 , Iafb18 , I03463 , I7ecef )
Dependency update
- The
lifecycle-viewmodel-compose
artifact now depends on Compose 1.6.0. - Lifecycle now depends on Profile Installer 1.3.1 .
Version 2.8.0-alpha03
20 марта 2024 г.
androidx.lifecycle:lifecycle-*:2.8.0-alpha03
is released. Version 2.8.0-alpha03 contains these commits .
Новые возможности
ViewModel.viewModelScope
is now an overridable constructor parameter, allowing you to inject your own dispatcher andSupervisorJob()
or to override the default by using thebackgroundScope
available withinrunTest
. ( 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 Multiplatform Compatibility
The lifecycle-viewmodel
artifact and APIs like ViewModel
, ViewModelStore
, ViewModelStoreOwner
, and ViewModelProvider
are now shipped in artifacts compatible with Kotlin Multiplatform. ( b/214568825 )
To accommodate this change, methods such as those on ViewModelProvider
that took a java.lang.Class<T>
now have an equivalent method that takes a kotlin.reflect.KClass<T>
.
Binary compatibility on Android has been maintained, but there are a few notable changes when comparing the Android API surface to the common API surface:
- Constructing a
ViewModelProvider
instance is now done through theViewModelProvider.create()
methods rather than directly calling its constructor. -
ViewModelProvider.NewInstanceFactory
andViewModelProvider.AndroidViewModelFactory
are only available on Android.- Custom Factories are recommended to extend from
ViewModelProvider.Factory
and use thecreate
method that takes aCreationExtras
or use theviewModelFactory
Kotlin DSL.
- Custom Factories are recommended to extend from
- Using
ViewModelProvider
without a custom factory on non-JVM platforms will result in anUnsupportedOperationException
. On JVM platforms, compatibility is preserved by using the no-args ViewModel constructor if a custom factory is not provided. -
viewModelScope
will fallback to anEmptyCoroutineContext
in platforms whereDispatchers.Main
is not available (eg, Linux).
Изменения поведения
-
InitializerViewModelFactory
(includingviewModelFactory
builder function) will now throw anIllegalArgumentException
if ainitializer
with the sameclazz: KClass<VM : ViewModel>
has already been added. ( Ic3a36 )
Исправления ошибок
-
ViewModel.getCloseable
now handles duplicated keys: if thekey
already has anAutoCloseable
resource associated with it, the old resource will be replaced and closed immediately. ( Ibeb67 ) - Accessing the
viewModelScope
of aViewModel
is now thread safe. ( If4766 , b/322407038 )
Внешний вклад
-
LocalLifecycleOwner
moved from Compose UI to lifecycle-runtime-compose so that its Compose-based helper APIs can be used outside of Compose UI. Thanks Jake Wharton for the contribution. ( I6c41b , b/328263448 )
Version 2.8.0-alpha02
21 февраля 2024 г.
androidx.lifecycle:lifecycle-*:2.8.0-alpha02
is released. Version 2.8.0-alpha02 contains these commits.
Новые возможности
- The
dropUnlessResumed
anddropUnlessStarted
APIs have been added which allow you to drop click or other events that occur even after theLifecycleOwner
has dropped below the givenLifecycle.State
. For example, this can be used with Navigation Compose to avoid handling click events after a transition to another screen has already begun:onClick: () -> Unit = dropUnlessResumed { navController.navigate(NEW_SCREEN) }
( Icba83 , b/317230685 )
Kotlin Conversions
-
ViewModel
is now written in Kotlin ( I16f26 , b/214568825 ) - The
lifecycle-viewmodel-ktx
kotlin extensions have now been moved to the base lifecycle module. ( Id787b , b/274800183 ) - The
lifecycle-runtime-ktx
kotlin extensions have now been moved to the base lifecycle module. ( Ic3686 , b/274800183 ) - The
lifecycle-livedata-core-ktx
kotlin extensions have now been moved to the base lifecycle module. ( I54a3d , b/274800183 )
Kotlin Multiplatform Compatibility
- The core Lifecycle APIs in
Lifecycle
,LifecycleOwner
,LifecycleObserver
,Lifecycle.State
,Lifecycle.Event
, andLifecycleRegistry
are now shipped in artifacts compatible with Kotlin Multiplatform. ( b/317249252 )
Изменения API
- Calling
LifecycleStartEffect
andLifecycleResumeEffect
without a key is now an error, following the same convention as theDisposableEffect
API that these APIs mirror. ( Ib0e0c , b/323518079 ) -
ViewModel
now usesAutoCloseable
instead ofCloseable
. That is a backward compatible change. ( I27f8e , b/214568825 ) - Deprecated
LiveDataReactiveStreams.toPublisher(lifecycleOwner, liveData)
in favor ofLiveData.toPublisher(lifecycleOwner)
. ( Iabe29 , b/262623005 )
Внешний вклад
- Thanks Ivan Matkov from Jetbrains for helping move Lifecycle to Kotlin Multiplatform. ( aosp/2926690 , I0c5ac , If445d )
Version 2.8.0-alpha01
24 января 2024 г.
androidx.lifecycle:lifecycle-*:2.8.0-alpha01
is released. Version 2.8.0-alpha01 contains these commits.
Новые возможности
-
ViewModel
now supports addingCloseable
objects with akey
that allows retrieving them viagetCloseable()
. ( I3cf63 )
Version 2.7
Version 2.7.0
10 января 2024 г.
androidx.lifecycle:lifecycle-*:2.7.0
is released. Version 2.7.0 contains these commits.
Important changes since 2.6.0
-
TestLifecycleOwner
now includes a suspending functionsetCurrentState()
which ensures that the state change and allLifecycleObserver
callbacks are completed before returning. Notably, unlike setting thecurrentState
property directly, this does not userunBlocking
, making it safe to use within a coroutine such as one provided byrunTest
. - The
LiveData
extensions ofmap
andswitchMap
now mirror the behavior ofdistinctUntilChanged
- if theLiveData
has avalue
set, themap
/switchMap
function will be immediately called to populate thevalue
of the returnedLiveData
. This ensures that the initial value will be set as part of the first composition (when used withobserveAsState()
), but does not change the observation behavior - updates values from the sourceLiveData
will still only apply once you start observing theLiveData
. - This release fixes an issue where
SavedStateHandle
would not properly restore customParcelable
classes 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
, andgetStateFlow
now specifically calls this limitation out. - The proguard keep rules associated with
LifecycleObserver
have been removed. This means that proguarded code that wishes to use APIs via reflection (such as using the long since deprecated@OnLifecycleEvent
annotation) 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 aFlow
ofLifecycle.Event
via theLifecycle.asFlow()
extension method. - Jetpack Compose users can now use
LifecycleEventEffect
to 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
LifecycleStartEffect
andLifecycleResumeEffect
to handle pairs of events - started to stopped and resumed to paused, respectively. This API mirrors the one found inDisposableEffect
and 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.State
can now be observed via theLifecycle.currentStateFlow
property, which returns aStateFlow
where thevalue
is the currentLifecycle.State
. - Jetpack Compose users can use the
Lifecycle.currentStateAsState()
extension to directly exposeLifecycle.State
as ComposeState
. This is equivalent (and a shorter alternative) tolifecycle.currentStateFlow.collectAsState()
.
See Collect lifecycle state with flows for more information.
Version 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
SavedStateHandle
would not properly restore customParcelable
classes 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
, andgetStateFlow
now specifically calls this limitation out. ( I0b55a )
Version 2.7.0-rc01
15 ноября 2023 г.
androidx.lifecycle:lifecycle-*:2.7.0-rc01
is released. Version 2.7.0-rc01 contains these commits.
Исправления ошибок
-
LifecycleStartEffect
andLifecycleResumeEffect
now correctly dispose and recreate the effect block if theLifecycleOwner
is changed. ( Ia25c6 )
Version 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.
Version 2.7.0-alpha03
18 октября 2023 г.
androidx.lifecycle:lifecycle-*:2.7.0-alpha03
is released. Version 2.7.0-alpha03 contains these commits.
Новые возможности
-
lifecycle-runtime-testing
now contains a new Lint check to avoid setting theLifecycle.State
of theTestLifecycleOwner
by using thecurrentState
field when inside of a coroutine. The Lint check now suggests the suspendingsetCurrentState
which allows setting theLifecycle.State
without blocking. ( Icf728 , b/297880630 )
Исправления ошибок
- Fixed an issue with
LiveData.switchMap
where returning the sameLiveData
instance both on the initial call and a subsequent call would prevent theLiveData
instance from being added as a source. ( Ibedcba7 )
Version 2.7.0-alpha02
6 сентября 2023 г.
androidx.lifecycle:lifecycle-*:2.7.0-alpha02
is released. Version 2.7.0-alpha02 contains these commits.
Новые возможности
-
TestLifecycleOwner
now includes the suspending functionsetCurrentState()
to give users the option of usingTestLifecycleOwner
from within a coroutine such as one provided byrunTest
. ( I329de , b/259344129 )
Изменения API
- All files from the
lifecycle-livedata-ktx
modules have been moved into the mainlifecycle-livedata
module. ( I10c6f , b/274800183 )
Изменения поведения
- The
LiveData.map()
andLiveData.switchMap()
extensions now sets thevalue
of the returnedLiveData
if the previousLiveData
has 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 theCloseable
if theViewModel
has already received a call toonCleared()
. ( I4712e , b/280294730 )
Исправления ошибок
- From Lifecycle
2.6.2
: Fixed an issue whereSavedStateHandle
would 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 betweenrememberSaveable
and Navigation Compose'sNavHost
. ( aosp/2729289 )
Version 2.7.0-alpha01
26 июля 2023 г.
androidx.lifecycle:lifecycle-*:2.7.0-alpha01
is released. Version 2.7.0-alpha01 contains these commits.
Изменения API
-
Lifecycle.State
is now Compose-observable viaLifecycle.currentStateFlow
, which returns aStateFlow
where thevalue
is the currentLifecycle.State
. ( Ib212d , b/209684871 ) -
Lifecycle.Event
s can now able to be observed as aFlow
withLifecycle.asFlow().
( If2c0f , b/176311030 ) -
LifecycleResumeEffect
API has been added to run ComposeSideEffect
s based on bothLifecycle.Event.ON_RESUME
andLifecycle.Event.ON_PAUSE
event callbacks. ( I60386 , b/235529345 ) -
LifecycleStartEffect
API has been added to run ComposeSideEffect
s based onLifecycle.Event.ON_START
andLifecycle.Event.ON_STOP
event callbacks. ( I5a8d1 , b/235529345 ) -
LifecycleEventEffect
API has been added to run ComposeSideEffect
s based onLifecycle.Event
. ( Ic9794 , b/235529345 ) -
Lifecycle.collectAsState()
extension has been added to directly exposeLifecycle.State
as ComposeState
. This is equivalent (and a shorter alternative) tolifecycle.currentStateFlow.collectAsState()
. ( I11015 , b/235529345 )
Исправления ошибок
- The
LiveData.distinctUntilChanged()
extension now sets thevalue
of the returnedLiveData
if the previousLiveData
has had a value set on it. This does not change the observation behavior - updated values from the sourceLiveData
will still only apply once you start observing theLiveData
returned fromdistinctUntilChanged()
. ( Ib482f ) - The proguard keep rules associated with
LifecycleObserver
have 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 )
Version 2.6
Version 2.6.2
6 сентября 2023 г.
androidx.lifecycle:lifecycle-*:2.6.2
is released. Version 2.6.2 contains these commits.
Исправления ошибок
- Fixed an issue where
SavedStateHandle
would 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 betweenrememberSaveable
and Navigation Compose'sNavHost
. ( aosp/2729289 )
Version 2.6.1
22 марта 2023 г.
androidx.lifecycle:lifecycle-*:2.6.1
is released. Version 2.6.1 contains these commits.
Обновления зависимостей
-
lifecycle-viewmodel-savedstate
now depends on SavedState1.2.1
. ( cd7251 ) - Lifecycle now depends on ProfileInstaller
1.3.0
. ( f9d30b )
Version 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
-
LiveData
now includes a newisInitialized
property that indicates whether an explicit value has ever been set on theLiveData
, allowing you to distinguish betweenliveData.value
returningnull
because no value has ever been set or an explicitnull
value. -
MediatorLiveData
now includes a constructor to set an initial value. - Added a new extension on
StateFlow
andFlow
ofcollectAsStateWithLifecycle()
that collect from flows and represents its latest value as Compose State in a lifecycle-aware manner. -
Lifecycle.launchWhenX
methods andLifecycle.whenX
methods 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
onChanged
method of aObserver
created in Kotlin now matches the nullability of the generic type. If you wantObserver.onChanged()
to accept a nullable type, you must instantiate theObserver
with 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
Version 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 thevalue
of the returnedLiveData
if the previousLiveData
has had a value set on it. This does not change the observation behavior - updated values from the sourceLiveData
will still only apply once you start observing theLiveData
returned fromdistinctUntilChanged()
. ( Ib482f )
Version 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
-
LifecycleOwner
is now written in Kotlin. This is a source incompatible change for classes written in Kotlin - they must now override thelifecycle
property rather than implementing the previousgetLifecycle()
function. ( I75b4b , b/240298691 ) -
ViewModelStoreOwner
is now in Kotlin. This is a source incompatible change for classes written in Kotlin - they must now override theviewModelStore
property rather than implementing the previousgetViewModelStore()
function. ( I86409 , b/240298691 ) - The Kotlin extension on
LifecycleOwner
that provides thelifecycleScope
field has been moved to thelifecycle-common
artifact fromlifecycle-runtime-ktx
. ( I41d78 , b/240298691 ) - The Kotlin extension on
Lifecycle
that provides thecoroutineScope
field has been moved to thelifecycle-common
artifact 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
-
Transformations
is 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.Function
method are deprecated and replaced with the versions that take a KotlinFunction1
. This change maintains binary compatibility. ( I8e14f ) -
ViewTreeViewModelStoreOwner
is 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 onView
ofandroidx.lifecycle.setViewTreeViewModelStoreOwner
andandroidx.lifecycle.findViewTreeViewModelStoreOwner
to 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
HasDefaultViewModelProviderFactory
interface is now written in Kotlin. This is a source incompatible change for classes written in Kotlin - they must now override thedefaultViewModelProviderFactory
anddefaultViewModelCreationExtras
properties rather than implementing the previous corresponding functions. ( Iaed9c , b/240298691 ) -
Observer
is now written in Kotlin. ItsonChanged()
method now uses the namevalue
for its parameter. ( Iffef2 , I4995e , b/240298691 ) -
AndroidViewModel
,AbstractSavedStateViewModelFactory
,LifecycleService
,ServiceLifecycleDispatcher
, andProcessLifecycleOwner
are 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.
Новые возможности
-
LiveData
now includes a newisInitialized
property that indicates whether an explicit value has ever been set on theLiveData
, allowing you to distinguish betweenliveData.value
returningnull
because no value has ever been set or an explicitnull
value. ( Ibd018 )
Изменения API
- The
collectAsStateWithLifecycle()
APIs oflifecycle-runtime-compose
are no longer in experimental status. ( I09d42 , b/258835424 ) -
Lifecycle.launchWhenX
methods andLifecycle.whenX
methods 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
-
ViewTreeLifecycleOwner
is 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 onView
ofandroidx.lifecycle.setViewTreeLifecycleOwner
andandroidx.lifecycle.findViewTreeLifecycleOwner
to 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 ) -
LiveDataReactiveStreams
is now written in Kotlin. The Kotlin extensions previously inlifecycle-reactivestreams-ktx
have been moved into thelifecycle-reactivestreams
module 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
, andViewModelStore
are now written in Kotlin ( Iadffd , ( I60034 , I8c52c , I9593d , I01fe1 , I59a23 , b/240298691 )
Исправления ошибок
-
SavedStateHandle
no longer crashes with aClassCastException
when callingget()
with the incorrect class type. ( I6ae7c )
Version 2.6.0-alpha03
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 )
Version 2.6.0-alpha02
7 сентября 2022 г.
androidx.lifecycle:lifecycle-*:2.6.0-alpha02
is released. Version 2.6.0-alpha02 contains these commits.
Изменения API
-
MediatorLiveData
now includes a constructor to set an initial value. ( Ib6cc5 , b/151244085 )
Исправления ошибок
-
Lifecycle
artifacts 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 acallbackFlow
rather than using its ownChannel
implementation to ensure thread-safety and context preservation. ( I4a8b2 , b/200596935 ) -
FlowLiveData
'sasLiveData
function will now preserve the initial value of aStateFlow
when creating the newLiveData
object. ( I3f530 , b/157380488 ) - From Lifecycle
2.5.1
: Custom implementations ofAndroidViewModelFactory
now correctly calls thecreate(modelClass)
function when using the stateful constructor withLifecycle
2.4+ ( I5b315 , b/238011621 )
Version 2.6.0-alpha01
29 июня 2022 г.
androidx.lifecycle:lifecycle-*:2.6.0-alpha01
is released. Version 2.6.0-alpha01 contains these commits.
Новые возможности
- Added a new extension on
StateFlow
andFlow
ofcollectAsStateWithLifecycle
that 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 )
Version 2.5
Version 2.5.1
27 июля 2022 г.
androidx.lifecycle:lifecycle-*:2.5.1
is released. Version 2.5.1 contains these commits.
Исправления ошибок
- Custom implementations of
AndroidViewModelFactory
now correctly call thecreate(modelClass)
function when using the statefulAndroidViewModelFactory
constructor withLifecycle
2.4+. ( I5b315 , b/238011621 )
Version 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
SavedStateHandle
now offers agetStateFlow()
API that returns a KotlinStateFlow
for monitoring value changes as an alternative to usingLiveData
.ViewModel CreationExtras - when writing a custom
ViewModelProvider.Factory
, it is no longer required to extendAndroidViewModelFactory
orAbstractSavedStateViewModelFactory
to gain access to anApplication
orSavedStateHandle
, respectively. Instead, these fields are provided to everyViewModelProvider.Factory
subclass asCreationExtras
via the new overload ofcreate
:create(Class<T>, CreationExtras)
. These extras are provided automatically by your Activity or Fragment when using Activity1.5.0
and 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-viewmodel
now provides aviewModelFactory
Kotlin DSL that allows you define yourViewModelProvider.Factory
in terms of one or more lambda initializers, one for each particularViewModel
class your custom factory supports, usingCreationExtras
as 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-compose
now offers aviewModel()
API that takes a lambda factory for creating aViewModel
instance 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-compose
artifact now contains new experimental APIs inSavedStateHandle.saveable
that allowrememberSaveable
like behavior backed by theSavedStateHandle
of 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 moreCloseable
objects to theViewModel
that will be closed when theViewModel
is 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
CoroutineScope
that 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
ViewModel
constructor 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 }
Behavior changes
- Attempting to move the
Lifecycle.State
fromINITIALIZED
toDESTROYED
will now always throw anIllegalStateException
regardless of whether theLifecycle
has an attached observer. -
LifecycleRegistry
will now clear their observers when they reach theDESTROYED
state.
Version 2.5.0-rc02
June 15, 2022
androidx.lifecycle:lifecycle-*:2.5.0-rc02
is released. Version 2.5.0-rc02 contains these commits.
Исправления ошибок
-
ViewModelProvider
will no longer crash when mixing previous versions of compileOnly Lifecycle dependencies with versions 2.5+. ( I81a66 , b/230454566 )
Version 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 aNullPointerException
when passed anull
source instead of propagating thenull
source to observers.( Ibd0fb , b/123085232 )
Version 2.5.0-beta01
April 20, 2022
androidx.lifecycle:lifecycle-*:2.5.0-beta01
is released. Version 2.5.0-beta01 contains these commits.
Изменения API
- Added
SavedStateHandle.saveable
property delegates to use property names as keys for persisting state into theSavedStateHandle
( I8bb86 , b/225014345 )
Исправления ошибок
- Fixed an issue where nesting one
NavHost
within anotherNavHost
in a non-primary bottom navigation tab would lead to anIllegalStateException
when 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
MutableState
overload toSavedStateHandle.saveable
for parity withrememberSaveable
( I38cfe , b/224565154 )
Изменения API
-
CreationExtras
is now abstract instead of sealed. ( Ib8a7a )
Исправления ошибок
- Fixed an
IllegalStateException: Already attached to lifecycleOwner
error 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-compose
module now providesSavedStateHandleSaver
, an experimental API that ensures values in aSavedStateHandle
are integrated correctly with the same saved instance state thatrememberSaveable
uses. ( Ia88b7 , b/195689777 )
Изменения API
- Fixed a compatibility issue with Lifecycle 2.3 and newer Lifecycle versions in Java. ( I52c8a , b/219545060 )
Исправления ошибок
-
SavedStateViewFactory
now supports usingCreationExtras
even 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
-
SavedStateHandle
now offers agetStateFlow()
API that returns a KotlinStateFlow
for monitoring value changes as an alternative to usingLiveData
. ( Iad3ab , b/178037961 )
Version 2.5.0-alpha03
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 moreCloseable
objects to theViewModel
that will be closed when theViewModel
is cleared without requiring any manual work inonCleared()
. ( I55ea0 ) -
lifecycle-viewmodel
now provides anInitializerViewModelFactory
that allows you to add lambda for handling particularViewModel
classes, usingCreationExtras
as the primary data source. ( If58fc , b/216687549 ) -
lifecycle-viewmodel-compose
now offers aviewModel()
API that takes a lambda factory for creating aViewModel
instance without requiring the creation of a customViewModelProvider.Factory
. ( I97fbb , b/216688927 )
Изменения API
- You can now create a
ViewModel
withCreationExtras
vialifecycle-viewmodel-compose
. ( I08887 , b/216688927 )
Behavior changes
- Attempting to move the
Lifecycle.State
fromINITIALIZED
toDESTROYED
will now always throw anIllegalStateException
regardless of whether theLifecycle
has an attached observer. ( I7c390 , b/177924329 ) -
LifecycleRegistry
will now clear their observers when they reach theDESTROYED
state. ( I4f8dd , b/142925860 )
Version 2.5.0-alpha02
9 февраля 2022 г.
androidx.lifecycle:lifecycle-*:2.5.0-alpha02
is released. Version 2.5.0-alpha02 contains these commits.
Изменения API
-
SavedStateHandle
andSavedStateViewModelFactory
have been converted to Kotlin. This has improved the nullability of the generics in both classes. ( Ib6ce2 , b/216168263 , I9647a , b/177667711 ) - The
LiveData
switchMap
function parameter can now have a nullable output. ( I40396 , b/132923666 ) - The
LiveData
-ktx extensions are now annotated with@CheckResult
to enforce that the result is used when calling these functions. ( Ia0f05 , b/207325134 )
Behavior changes
-
SavedStateHandle
now properly stores the defaultValue when no value for the specified key exists. ( I1c6ce , b/178510877 )
Исправления ошибок
- From Lifecycle
2.4.1
: Updatedlifecycle-process
to depend on Startup 1.1.1 to ensure that fixes that preventProcessLifecycleInitializer
from throwing aStartupException
are available by default. ( Ib01df , b/216490724 ) - There is now an improved error message when custom
AndroidViewModel
classes have parameters in the wrong order and attempt to create aViewModel
. ( I340f7 , b/177667711 ) - You can now create a view model via
CreationExtras
using theAndroidViewModelFactory
without setting an application. ( I6ebef , b/217271656 )
Version 2.5.0-alpha01
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
: thisString
provides access to the custom key you passed toViewModelProvider.get()
. -
ViewModelProvider.AndroidViewModelFactory.APPLICATION_KEY
provides access to theApplication
class. -
SavedStateHandleSupport.SAVED_STATE_REGISTRY_OWNER_KEY
provides access to theSavedStateRegistryOwner
that is being used to construct this ViewModel. -
SavedStateHandleSupport.VIEW_MODEL_STORE_OWNER_KEY
provides access to theViewModelStoreOwner
that is being used to construct this ViewModel. -
SavedStateHandleSupport.DEFAULT_ARGS_KEY
provides access to theBundle
of 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 идем вперед.
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
SavedStateHandle
would reappear after process death and recreation, even if it was specifically removed from theSavedStateHandle
. As a consequence of this,SavedStateHandle
will no longer merge default values and restored values together, instead only using the restored values as the source of truth. ( I53a4b )
Version 2.4
Version 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 aSavedStateHandle
would re-appear after process death and recreation, even if it was specifically removed from theSavedStateHandle
. As a consequence of this,SavedStateHandle
will no longer merge default values and restored values together, instead only using the restored values as the source of truth. ( I53a4b ) -
lifecycle-process
now depends on Androidx Startup 1.1.1 which fixed a regression in where usingProcessLifecycleInitializer
would cause anStartupException
. ( b/216490724 )
Version 2.4.0
27 октября 2021 г.
androidx.lifecycle:lifecycle-*:2.4.0
is released. Version 2.4.0 contains these commits.
Important changes since 2.3.0
-
@OnLifecycleEvent
was deprecated.LifecycleEventObserver
orDefaultLifecycleObserver
should be used instead. -
androidx.lifecycle:lifecycle-viewmodel-compose
library was added. It providesviewModel()
composable andLocalViewModelStoreOwner
.- Source-breaking change :
ViewModelProvider
has been rewritten in Kotlin.ViewModelProvider.Factory.create
method 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. -
DefaultLifecycleObserver
was moved fromlifecycle.lifecycle-common-java8
tolifecycle.lifecycle-common
.lifecycle.lifecycle-common-java8
doesn'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-ktx
have been moved to thelifecycle-viewmodel
module. lifecycle-process
now usesandroidx.startup
to initialize theProcessLifecycleOwner
.Previously, this was being done by
androidx.lifecycle.ProcessLifecycleOwnerInitializer
.If you used
tools:node="remove"
theContentProvider
being 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>
Version 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.
Version 2.4.0-beta01
September 15, 2021
androidx.lifecycle:lifecycle-*:2.4.0-beta01
is released. Version 2.4.0-beta01 contains these commits.
Изменения API
-
@OnLifecycleEvent
was deprecated.LifecycleEventObserver
orDefaultLifecycleObserver
should be used instead. ( I5a8fa ) - DefaultLifecycleObserver was moved from
androidx.lifecycle.lifecycle-common-java8
toandroidx.lifecycle.lifecycle-common
.androidx.lifecycle.lifecycle-common-java8
doesn'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-ktx
have been moved to thelifecycle-viewmodel
module. ( I6d5b2 )
Внешний вклад
Version 2.4.0-alpha03
August 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.create
method no longer allows nullable generic. ( I9b9f6 )
Изменения поведения
- The
Lifecycle.repeatOnLifecycle
:block
is now always invoked serially when repeating execution. ( Ibab33 )
Внешний вклад
- Thanks chao2zhang for fixing the code snippets in the
repeatOnLifecycle
documentation. #205 .
Version 2.4.0-alpha02
16 июня 2021 г.
androidx.lifecycle:lifecycle-*:2.4.0-alpha02
is released. Version 2.4.0-alpha02 contains these commits.
Новые возможности
- Added a new
RepeatOnLifecycleWrongUsage
lint check tolifecycle-runtime-ktx
that detects whenrepeateOnLifecycle
is incorrectly used inonStart()
oronResume()
. ( 706078 , b/187887400 )
Изменения API
- The
LifecycleOwner.addRepeatingJob
API is removed in favor ofLifecycle.repeatOnLifecycle
that respects structured concurrency and is easier to reason about. ( I4a3a8 ) - Make
ProcessLifecycleInitializer
public so otherandroidx.startup.Initializer
s can use these as dependencies. ( I94c31 )
Исправления ошибок
- Fixed an issue with the
NullSafeMutableLiveData
lint check when the field has modifiers. ( #147 , b/183696616 ) - Fixed another issue with the
NullSafeMutableLiveData
lint check when using generics. ( #161 , b/184830263 )
Внешний вклад
- Thanks maxsav for improving the
NullSafeMutableLiveData
lint check. ( #147 , b/183696616 ) - Thanks kozaxinan for improving the
NullSafeMutableLiveData
lint check. ( #161 , b/184830263 )
Version 2.4.0-alpha01
24 марта 2021 г.
androidx.lifecycle:lifecycle-*:2.4.0-alpha01
is released. Version 2.4.0-alpha01 contains these commits.
Изменения поведения
lifecycle-process
now usesandroidx.startup
to initialize theProcessLifecycleOwner
.Previously, this was being done by
androidx.lifecycle.ProcessLifecycleOwnerInitializer
.If you used
tools:node="remove"
theContentProvider
being 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.flowWithLifecycle
API that emits values from the upstream Flow when the lifecycle is at least in a certain state using theLifecycle.repeatOnLifecycle
API. This is an alternative to the also newLifecycleOwner.addRepeatinJob
API. ( I0f4cd )
Исправления ошибок
- From Lifecycle 2.3.1 : The
NonNullableMutableLiveData
lint 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.
Breaking API Changes
-
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
June 2, 2021
androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha06
is released. Версия 1.0.0-alpha06 содержит эти коммиты.
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. Версия 1.0.0-alpha05 содержит эти коммиты.
Новые возможности
- 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
April 7, 2021
androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha04
is released. Версия 1.0.0-alpha04 содержит эти коммиты.
Dependency Changes
- This version allows
androidx.hilt:hilt-navigation-compose
andandroidx.navigation:navigation-compose
to sync dependencies onandroidx.compose.compiler:compiler:1.0.0-beta04
andandroidx.compose.runtime:runtime:1.0.0-beta04
. For 1.0.0, it is required that the compiler and runtime match.
Версия 1.0.0-альфа03
March 10, 2021
androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha03
is released. Версия 1.0.0-alpha03 содержит эти коммиты.
Изменения API
-
LocalViewModelStoreOwner.current
now returns a nullableViewModelStoreOwner
to better determine whether aViewModelStoreOwner
is available in the current composition. APIs that require aViewModelStoreOwner
, such asviewModel()
andNavHost
, still throw an exception if aViewModelStoreOwner
is not set. ( Idf39a )
Lifecycle-Viewmodel-Compose Version 1.0.0-alpha02
24 февраля 2021 г.
androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha02
is released. Версия 1.0.0-alpha02 содержит эти коммиты.
Изменения API
-
LocalViewModelStoreOwner
now has aprovides
functions 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. Версия 1.0.0-alpha01 содержит эти коммиты.
Новые возможности
- The
viewModel()
composable andLocalViewModelStoreOwner
were moved fromandroidx.compose.ui.viewinterop
to this artifact in theandroidx.lifecycle.viewmodel.compose
package. ( I7a374 )
Version 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
NonNullableMutableLiveData
lint rule can now properly differentiate between field variables with different nullability. ( b/169249668 )
Version 2.3.0
Version 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
-
SavedStateHandle
support for non-parcelable classes :SavedStateHandle
now supports lazy serialization by allowing you to callsetSavedStateProvider()
for a given key, providing aSavedStateProvider
that will get a callback tosaveState()
when theSavedStateHandle
is asked to save its state. See Saving non-parcelable classes . - Lifecycle Behavior Enforcement :
- LifecycleRegistry now enforces
DESTROYED
as a terminal state. -
LifecycleRegistry
now 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. ForLifecycleRegistry
objects 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 thisLifecycleRegistry
is 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.Event
for generating theEvent
given aState
and transition direction. Added thegetTargetState()
method that provides theState
that the Lifecycle will transition to directly following theEvent
. -
withStateAtLeast
: AddedLifecycle.withStateAtLeast
APIs 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 ) -
ViewTree
APIs : A newViewTreeLifecycleOwner.get(View)
andViewTreeViewModelStoreOwner.get(View)
API allows you to retrieve the containingLifecycleOwner
andViewModelStoreOwner
, respectively, given aView
instance. You must upgrade to Activity1.2.0
and Fragment1.3.0
, and AppCompat 1.3.0-alpha01 or higher to populate this correctly. ThefindViewTreeLifecycleOwner
andfindViewTreeViewModelStoreOwner
Kotlin extensions are available inlifecycle-runtime-ktx
andlifecycle-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.
Version 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 ofSavedStateHandle
is 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 )
Version 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 )
Documentation Changes
- The
liveData
builder 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
NullSafeMutableLiveData
Lint 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.Event
for generating theEvent
given aState
and transition direction. Added thegetTargetState()
method that provides theState
that the Lifecycle will transition to directly following theEvent
. ( I00887 ) - Added
Lifecycle.withStateAtLeast
APIs 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
DESTROYED
as a terminal state. ( I00887 ) -
LifecycleRegistry
now 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. ForLifecycleRegistry
objects 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 thisLifecycleRegistry
is accessed from different threads ( Ie7280 , b/137392809 )
Исправления ошибок
- Fixed a crash in
NullSafeMutableLiveData
. ( b/159987480 ) - Fixed an
ObsoleteLintCustomCheck
for 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.
Исправления ошибок
-
LiveData
now 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 )
Version 2.3.0-alpha04
10 июня 2020 г.
androidx.lifecycle:lifecycle-*:2.3.0-alpha04
is released. Version 2.3.0-alpha04 contains these commits.
Исправления ошибок
- Fixed a crash in the
NonNullableMutableLiveData
Lint check. ( b/157294666 ) - The
NonNullableMutableLiveData
Lint check now covers significantly more cases where anull
value was set on aMutableLiveData
with a non-null type parameter. ( b/156002218 )
Version 2.3.0-alpha03
May 20, 2020
androidx.lifecycle:lifecycle-*:2.3.0-alpha03
are released. Version 2.3.0-alpha03 contains these commits.
Новые возможности
-
SavedStateHandle
now supports lazy serialization by allowing you to callsetSavedStateProvider()
for a given key, providing aSavedStateProvider
that will get a callback tosaveState()
when theSavedStateHandle
is asked to save its state. ( b/155106862 ) - A new
ViewTreeViewModelStoreOwner.get(View)
API allows you to retrieve the containingViewModelStoreOwner
given aView
instance. You must upgrade to Activity1.2.0-alpha05
, Fragment1.3.0-alpha05
, and AppCompat1.3.0-alpha01
to populate this correctly. AfindViewModelStoreOwner()
Kotlin extension has been added tolifecycle-viewmodel-ktx
. ( aosp/1295522 )
Исправления ошибок
- Fixed an issue that caused the
MutableLiveData
Lint checks released in Lifecycle2.3.0-alpha01
from being published alongside thelifecycle-livedata-core-ktx
artifact. ( b/155323109 )
Version 2.3.0-alpha02
29 апреля 2020 г.
androidx.lifecycle:lifecycle-*:2.3.0-alpha02
is released. Version 2.3.0-alpha02 contains these commits.
Изменения API
-
SavedStateViewModelFactory
now allows you to pass a nullApplication
to its constructor to better support cases where one is not readily available and support forAndroidViewModel
is not needed. ( aosp/1285740 )
Исправления ошибок
- Improved cold start performance by avoiding class verification failure on API 28 and lower devices. ( aosp/1282118 )
Version 2.3.0-alpha01
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 containingLifecycleOwner
given aView
instance. You must upgrade to Activity1.2.0-alpha01
and Fragment1.3.0-alpha01
to populate this correctly. AfindViewTreeLifecycleOwner
Kotlin extension is available inlifecycle-runtime-ktx
. ( aosp/1182361 , aosp/1182956 ) - Added a new Lint check that warns you when setting a
null
value on aMutableLiveData
that has been defined in Kotlin as non-null. This is available when using thelivedata-core-ktx
orlivedata-ktx
artifacts. ( aosp/1154723 , aosp/1159092 ) - A new
lifecycle-runtime-testing
artifact is available that provides aTestLifecycleOwner
that implementsLifecycleOwner
and provides a thread safe mutableLifecycle
. ( aosp/1242438 )
Исправления ошибок
- The
lifecycle-runtime
artifact now has a unique package name. ( aosp/1187196 )
Version 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
.
Version 2.2.0
January 22, 2020
androidx.lifecycle:lifecycle-*:2.2.0
is released. Version 2.2.0 contains these commits .
Important changes since 2.1.0
- Lifecycle Coroutine Integration : The new
lifecycle-runtime-ktx
artifact adds integration between Lifecycle and Kotlin coroutines. Thelifecycle-livedata-ktx
has 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 aFragment
orFragmentActivity
to the newViewModelProvider(ViewModelStoreOwner)
constructor to achieve the same functionality when using Fragment1.2.0
. -
lifecycle-extensions
Artifact Deprecation : With the above deprecation ofViewModelProviders.of()
, this release marks the deprecation of the last API inlifecycle-extensions
and this artifact should now be considered deprecated in its entirety. We strongly recommend depending on the specific Lifecycle artifacts you need (such aslifecycle-service
if you're usingLifecycleService
andlifecycle-process
if you're usingProcessLifecycleOwner
) rather thanlifecycle-extensions
as there will not be a future2.3.0
release 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
DefautLifecycleObserver
instead; 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
ViewModel
was stored inViewModelStore
and queried later with default factory. - Fix a usage of
Dispatchers.Main.immediate
inlaunchWhenCreated
and similar methods to be called synchronously during corresponding lifecycle event. ( aosp/1156203 )
External contributions
- 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 )
Version 2.2.0-rc01
October 23, 2019
androidx.lifecycle:lifecycle-*:2.2.0-rc01
is released. Version 2.2.0-rc01 contains these commits .
Исправления ошибок
- Fixed an issue where
launchWhenCreated
and related methods would run one frame later than the associated lifecycle method due to its use ofDispatchers.Main
instead ofDispatchers.Main.immediate
. ( aosp/1145596 )
External contributions
- Thanks to Nicklas Ansman for contributing the fix! ( aosp/1145596 )
Version 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
ProcessLifecycleOwner
and the activity'sLifecycleOwner
moving to started and resumed on Android 10 devices. ( aosp/1128132 ) - Fixed a regression introduced in Lifecycle
2.2.0-alpha05
which would cause aNullPointerException
when using version2.0.0
or2.1.0
oflifecycle-process
. ( b/141536990 )
Version 2.2.0-alpha05
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 ofliveData
now useDispatchers.Main.immediate
instead ofDispatchers.Main
. ( b/139740492 )
External contributions
- 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
ViewModelStoreOwner
can now optionally implementHasDefaultViewModelProviderFactory
to 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 aFragment
orFragmentActivity
to the newViewModelProvider(ViewModelStoreOwner)
constructor to achieve the same functionality. ( aosp/1009889 )
Version 2.2.0-alpha02
2 июля 2019 г.
androidx.lifecycle:*:2.2.0-alpha02
is released. The commits included in this version can be found here .
Изменения API
- Replaced
LiveDataScope.initialValue
withLiveDataScope.latestValue
which will track the current emitted value of theliveData
block. - Added a new overload to the
liveData
builder that receivestimeout
parameter as typeDuration
Version 2.2.0-alpha01
May 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
Version 1.0.0
January 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
ViewModel
classes to access and to contribute to the saved state. This object can be received in constructor ofViewModel
class and factories provided by default by Fragments and AppCompatActivity will injectSavedStateHandle
automatically. - AbstractSavedStateViewModelFactory was added. It allows you to create custom factories for your
ViewModel
and 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
October 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
IllegalStateException
when usingAbstractSavedStateViewModelFactory
. ( b/141225984 )
ViewModel-SavedState Version 1.0.0-alpha05
18 сентября 2019 г.
androidx.lifecycle:lifecycle-viewmodel-savedstate:1.0.0-alpha05
is released. Версия 1.0.0-alpha05 содержит эти коммиты .
Изменения API
-
SavedStateViewModelFactory
no longer extendsAbstractSavedStateViewModelFactory
andSavedStateHandle
is 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-savedstate
no longer depends onfragment
and the relatedSavedStateViewModelFactory(Fragment)
andSavedStateViewModelFactory(FragmentActivity)
constructors have been removed. Instead,SavedStateViewModelFactory
is 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
-
SavedStateVMFactory
is renamed toSavedStateViewModelFactory
. -
AbstractSavedStateVMFactory
is 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
ViewModels
can contribute to savedstate. To do that you use newly introduced viewmodel's factorySavedStateVMFactory
and your ViewModel should have a constructor that receivesSavedStateHandle
object as a parameter.
Version 2.1.0
Important changes since 2.0.0
- Added
LifecycleEventObserver
for the cases when a stream of lifecycle events is needed. It is a public API instead of a hiddenGenericLifecycleObserver
class. - Added ktx extensions for
LiveData.observe
methods andTransformations.*
methods. - Added
Transformations.distinctUntilChanged
, which creates a new LiveData object that does not emit a value until the sourceLiveData
value has been changed. - Added coroutine support in ViewModels by adding the extension property
ViewModel.viewModelScope
.
Version 2.1.0
5 сентября 2019 г.
androidx.lifecycle:lifecycle-*:2.1.0
is released. The commits included in this version can be found here .
Version 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 .
Version 2.1.0-beta01
May 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
liveData
extension functions for transformations and observations,ViewModel
initialisation with property delegation and others are stabilised and not going to change.
Version 2.1.0-alpha04
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 aViewModelStore
directly, rather than only aViewModelStoreOwner
. ( aosp/932932 )
Version 2.1.0-alpha03
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.KeyedFactory
was removed. Second interface in addition toViewModelProvider.Factory
didn't compose well with new features as property delegation in Kotlinby viewmodels {}
. ( aosp/914133 )
Version 2.1.0-alpha02
January 30, 2019
androidx.lifecycle 2.1.0-alpha02
is released.
Изменения API
-
LifecycleRegistry
now contains asetCurrentState()
method that replaces the now deprecatedsetState()
method. ( aosp/880715 )
Исправления ошибок
- Fixed an issue where mock
ViewModel
instances would crash when the containingViewModelStore
was cleared. b/122273087
Version 2.1.0-alpha01
December 17, 2018
androidx.lifecycle 2.1.0-alpha01
is released.
Новые возможности
- Added
LifecycleEventObserver
for the cases when a stream of lifecycle events is needed. It is a public api instead of a hiddenGenericLifecycleObserver
class. - Added ktx extensions for
LiveData.observe
methods andTransformations.*
methods. - Method
Transformations.distinctUntilChanged
was added. It creates a newLiveData
object that does not emit a value until the source LiveData value has been changed. - Coroutine support in ViewModels: extension property
ViewModel.viewModelScope
was added. - Added
ViewModelProvider.KeyedFactory
, a factory for ViewModels that receiveskey
andClass
increate
method.
Version 2.0.0
Version 2.0.0
September 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
Version 2.0.0-beta01
July 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
March 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 г.
Packaging Changes
New, much smaller dependencies are now available:
-
android.arch.lifecycle:livedata:1.1.0
-
android.arch.lifecycle:viewmodel:1.1.0
Изменения API
- The deprecated
LifecycleActivity
andLifecycleFragment
have now been removed - please useFragmentActivity
,AppCompatActivity
or supportFragment
. -
@NonNull
annotations have been added toViewModelProviders
andViewModelStores
-
ViewModelProviders
constructor has been deprecated - please use its static methods directly -
ViewModelProviders.DefaultFactory
has been deprecated - please useViewModelProvider.AndroidViewModelFactory
- The static
ViewModelProvider.AndroidViewModelFactory.getInstance(Application)
method has been added to retrieve a staticFactory
suitable for creatingViewModel
andAndroidViewModel
instances.
Жизненный цикл
This table lists all the artifacts in the androidx.lifecycle
group.
Артефакт | Стабильный выпуск | Кандидат на выпуск | Бета-версия | Альфа-релиз |
---|---|---|---|---|
жизненный цикл-* | 2.8.6 | - | - | 2.9.0-alpha03 |
lifecycle-viewmodel-compose | 2.8.6 | - | - | 2.9.0-alpha03 |
Объявление зависимостей
To add a dependency on Lifecycle, you must add the Google Maven repository to your project. Для получения дополнительной информации прочтите репозиторий Google Maven .
Добавьте зависимости для нужных вам артефактов в файл build.gradle
для вашего приложения или модуля:
Котлин
классный
dependencies { def lifecycle_version = "2.8.7" 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" // 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.8.7" 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") // 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.8.7" 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.8.7" 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") }
For more information about dependencies, see Add Build Dependencies .
Обратная связь
Ваши отзывы помогают сделать Jetpack лучше. Дайте нам знать, если вы обнаружите новые проблемы или у вас есть идеи по улучшению этой библиотеки. Пожалуйста, ознакомьтесь с существующими проблемами в этой библиотеке, прежде чем создавать новую. Вы можете добавить свой голос к существующей проблеме, нажав кнопку со звездочкой.
Дополнительную информацию см . в документации по системе отслеживания проблем .
Version 2.9
Version 2.9.0-alpha03
18 сентября 2024 г.
androidx.lifecycle:lifecycle-*:2.9.0-alpha03
is released. Version 2.9.0-alpha03 contains these commits .
Исправления ошибок
- From Lifecycle
2.8.6
: TheNullSafeMutableLiveData
Lint error has improved support for smart casts, avoiding false positives. ( 85fed6 , b/181042665 )
Обновления зависимостей
- From Lifecycle
2.8.6
: Lifecycle Runtime Compose now depends on Compose Runtime1.7.1
- Lifecycle Runtime now depends on ProfileInstaller
1.4.0
Version 2.9.0-alpha02
4 сентября 2024 г.
androidx.lifecycle:lifecycle-*:2.9.0-alpha02
is released. Version 2.9.0-alpha02 contains these commits .
Исправления ошибок
- From Lifecycle
2.8.5
: Update theandroidx.lifecycle.ReportFragment
ProGuard rules to allow obfuscation . ( ff898e1 )
Внешний вклад
- Move
androidx.compose.ui.platform.LocalLifecycleOwner
to common source set (KMP). Thanks Ivan Matkov from JetBrains for the contribution. ( 8cd5d03 ) - From Lifecycle
2.8.5
: SavedStateHandle.saveable` extension delegate now supports nullable values. Thanks Roman Kalukiewicz for the contribution. ( 0d78ea6 )
Version 2.9.0-alpha01
7 августа 2024 г.
androidx.lifecycle:lifecycle-*:2.9.0-alpha01
is released. Version 2.9.0-alpha01 contains these commits .
Kotlin Multiplatform
-
lifecycle-testing
is now KMP compatible. ( Iea41e ) - Add support for
linuxArm64
kotlin multiplatform target ( I139d3 , b/338268719 )
Новые возможности
- A new
androidx.lifecycle:lifecycle-viewmodel-testing
KMP artifact is available that provides aViewModelScenario
class for testing ViewModels in isolation, with support foronCleared
(all platforms) andSavedStateHandle
(Android only). ( 337f68d , c9b3409 , 9799a95c , b/264602919 ) - Creating a
ViewModel
withViewModelProvider
is now thread safe;@MainThread
annotations have been removed. ( Ifd978 , b/237006831 )
Изменения API
- Add the
CreationExtras.Key()
factory function to simplify the creation of anonymousCreationExtras.Key
objects. ( I970ee ) -
CreationExtras
now includes map-like operator overloads to enable idiomatic manipulation of content in Kotlin. It allows the use ofin
,+=
, and+
withCreationExtras
. ( Ib4353 ) -
CreationExtras
now implementsequals
,hashCode
, andtoString
methods. ( Ib4353 ) -
NewInstanceFactory
is now available on JVM Desktop and Android targets. ( d3d0892 ) - Inline extension property to expose underlying Application safely in Kotlin language version 2.0 ( I39df2 )
Исправления ошибок
- Removed manual outlining of access to new platform APIs since this happens automatically via API modeling when using R8 with AGP 7.3 or later (eg R8 version 3.3) and for all builds when using AGP 8.1 or later (eg D8 version 8.1). Clients who are not using AGP are advised to update to D8 version 8.1 or later. See this article for more details. ( If6b4c , b/345472586 )
Version 2.8
Version 2.8.6
18 сентября 2024 г.
androidx.lifecycle:lifecycle-*:2.8.6
is released. Version 2.8.6 contains these commits .
Исправления ошибок
- The
NullSafeMutableLiveData
Lint error has improved support for smart casts, avoiding false positives. ( 85fed6 , b/181042665 )
Обновления зависимостей
- Lifecycle Runtime Compose now depends on Compose Runtime
1.7.1
Version 2.8.5
4 сентября 2024 г.
androidx.lifecycle:lifecycle-*:2.8.5
is released. Version 2.8.5 contains these commits .
Исправления ошибок
- Update the
androidx.lifecycle.ReportFragment
ProGuard rules to allow obfuscation . ( ff898e1 )
Внешний вклад
-
SavedStateHandle.saveable
extension delegate now supports nullable values. Thanks Roman Kalukiewicz for the contribution. ( 0d78ea6 )
Version 2.8.4
24 июля 2024 г.
androidx.lifecycle:lifecycle-*:2.8.4
is released. Version 2.8.4 contains these commits .
Исправления ошибок
-
LiveData.asFlow()
now correctly handles cases where the returned Flow is immediately completed after receiving a value already set on theLiveData
(for example, when usingtake(1)
). ( I9c566 ) -
Lifecycle*Effect
completion is now idempotent (ie, if theonStopOrDispose
was called because of the Lifecycle being stopped, it won't be called a second time upon disposal unless the Lifecycle goes back up toSTARTED
again). ( I5f607 , b/352364595 )
Version 2.8.3
1 июля 2024 г.
androidx.lifecycle:lifecycle-*:2.8.3
is released. Version 2.8.3 contains these commits .
Исправления ошибок
- Fixed an issue with Lifecycle 2.8's backward compatibility with Compose 1.6.0 and lower when using code shrinking. ( aosp/3133056 , b/346808608 )
Version 2.8.2
12 июня 2024 г.
androidx.lifecycle:lifecycle-*:2.8.2
is released. Version 2.8.2 contains these commits .
Исправления ошибок
- Fixed
CompositionLocal LocalLifecycleOwner not present
errors when using Lifecycle 2.8.X with Compose 1.6.X or earlier - you can now use Lifecycle 2.8.2 with any version of Compose without any workarounds required. ( aosp/3105647 , b/336842920 ) -
ViewModelProvider
will no longer crash when mixing previous versions ofcompileOnly
Lifecycle dependencies with versions 2.8+, fixing issues with libraries such as LeakCanary. ( I80383 , b/341792251 )
Version 2.8.1
29 мая 2024 г.
androidx.lifecycle:lifecycle-*:2.8.1
is released. Version 2.8.1 contains these commits .
Исправления ошибок
-
lifecycle-viewmodel-compose
now only has a common dependency oncompose-runtime
, removing its common dependency oncompose-ui
. The Android artifact retains itscompose-ui
for compatibility. ( aosp/3079334 , b/339562627 ) -
ViewModel
'ssaveable
integration using property delegates now uses the class name as part of the auto-generated key, avoiding conflicts if multiple classes use the sameSavedStateHandle
. ( aosp/3063463 )
Version 2.8.0
14 мая 2024 г.
androidx.lifecycle:lifecycle-*:2.8.0
is released. Version 2.8.0 contains these commits .
Important changes since 2.7.0
-
LocalLifecycleOwner
has been moved from Compose UI tolifecycle-runtime-compose
so that its Compose-based helper APIs can be used outside of Compose UI. - The
lifecycle-runtime-compose
artifact now contains thedropUnlessResumed
anddropUnlessStarted
APIs which allow you to drop click or other events that occur even after theLifecycleOwner
has dropped below the givenLifecycle.State
. For example, this can be used with Navigation Compose to avoid handling click events after a transition to another screen has already begun:onClick: () -> Unit = dropUnlessResumed { navController.navigate(NEW_SCREEN) }
ViewModel.viewModelScope
is now an overridable constructor parameter, allowing you to inject your own dispatcher andSupervisorJob()
or to override the default by using thebackgroundScope
available withinrunTest
. ( 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
has been rewritten in Kotlin and now usesAutoClosable
instead ofCloseable
. It now supports addingAutoCloseable
objects with akey
that allows retrieving them viagetCloseable()
.Calling
LifecycleStartEffect
andLifecycleResumeEffect
without a key is now an error, following the same convention as theDisposableEffect
API that these APIs mirror.Deprecated
LiveDataReactiveStreams.toPublisher(lifecycleOwner, liveData)
in favor ofLiveData.toPublisher(lifecycleOwner)
.The
lifecycle-livedata-core-ktx
kotlin extensions have now been moved to thelifecycle-livedata-core
module.The
NullSafeMutableLiveData
has been refactored to avoid many false positives.
Lifecycle Kotlin Multiplatform Compatibility
The core Lifecycle APIs in Lifecycle
, LifecycleOwner
, LifecycleObserver
, Lifecycle.State
, Lifecycle.Event
, and LifecycleRegistry
are now shipped in artifacts compatible with Kotlin Multiplatform.
Artifacts impacted:
-
lifecycle-common
moves most APIs tocommon
and supports jvm and iOS in addition to Android. -
lifecycle-runtime
moves most APIs tocommon
and supports jvm and iOS in addition to Android. -
lifecycle-runtime-ktx
is now empty, with all APIs being moved intolifecycle-runtime
. -
lifecycle-runtime-compose
moves all APIs tocommon
and ships an Android artifact, matching the multiplatform support ofandroidx.compose
.
ViewModel Kotlin Multiplatform Compatibility
The lifecycle-viewmodel
artifact and APIs like ViewModel
, ViewModelStore
, ViewModelStoreOwner
, and ViewModelProvider
are now shipped in artifacts compatible with Kotlin Multiplatform.
To accommodate this change, methods such as those on ViewModelProvider
that took a java.lang.Class<T>
now have an equivalent method that takes a kotlin.reflect.KClass<T>
.
Binary compatibility on Android has been maintained, but there are a few notable changes when comparing the Android API surface to the common API surface:
- Constructing a
ViewModelProvider
instance is now done through theViewModelProvider.create()
methods rather than directly calling its constructor. -
ViewModelProvider.NewInstanceFactory
andViewModelProvider.AndroidViewModelFactory
are only available on Android.- Custom Factories are recommended to extend from
ViewModelProvider.Factory
and use thecreate
method that takes aCreationExtras
or use theviewModelFactory
Kotlin DSL.
- Custom Factories are recommended to extend from
- Using
ViewModelProvider
without a custom factory on non-JVM platforms will result in anUnsupportedOperationException
. On JVM platforms, compatibility is preserved by using the no-args ViewModel constructor if a custom factory is not provided. -
viewModelScope
will fallback to anEmptyCoroutineContext
in platforms whereDispatchers.Main
is not available (eg, Linux).
Artifacts impacted:
-
lifecycle-viewmodel
moves most APIs tocommon
and supports jvm and iOS in addition to Android. -
lifecycle-viewmodel-ktx
is now empty, with all APIs being moved intolifecycle-viewmodel
. -
lifecycle-viewmodel-compose
moves all APIs tocommon
and ships an Android artifact, matching the multiplatform support ofandroidx.compose
.
Изменения поведения
-
InitializerViewModelFactory
(includingviewModelFactory
builder function) will now throw anIllegalArgumentException
if ainitializer
with the sameclazz: KClass<VM : ViewModel>
has already been added. ( Ic3a36 )
Известные проблемы
-
lifecycle-*:2.8.0
requires a minimum Compose version of 1.7.0-alpha05 ( b/336842920 ).
Version 2.8.0-rc01
1 мая 2024 г.
androidx.lifecycle:lifecycle-*:2.8.0-rc01
is released. Version 2.8.0-rc01 contains these commits .
Исправления ошибок
- Fixed an issue where the Baseline Profile for
lifecycle-common
classes was not properly packaged. These are now packaged in thelifecycle-runtime
AAR. ( aosp/3038274 , b/322382422 ) - Fixed an unintentional ordering change in how
AutoCloseable
instances attached to a ViewModel are cleared - the previous order ofaddCloseable(String, AutoCloseable)
, thenaddClosable(AutoCloseable)
, thenonCleared()
has been restored. ( aosp/3041632 ) - Improve the default creation behavior for
viewModelScope
for native and JVM Desktop environments. ( aosp/3039221 )
Внешний вклад
- Thanks Victor Kropp for improving the checking for the main thread on JVM Desktop. ( aosp/3037116 )
Version 2.8.0-beta01
17 апреля 2024 г.
androidx.lifecycle:lifecycle-*:2.8.0-beta01
is released. Version 2.8.0-beta01 contains these commits .
Новые возможности
- The
lifecycle-runtime-compose
artifact is now compatible with Kotlin Multiplatform, moving its code tocommon
and ships an Android artifact, matching the multiplatform support forandroidx.compose
. ( If7a71 , I4f4a0 , b/331769623 )
Version 2.8.0-alpha04
3 апреля 2024 г.
androidx.lifecycle:lifecycle-*:2.8.0-alpha04
is released. Version 2.8.0-alpha04 contains these commits .
Новые возможности
- The
lifecycle-viewmodel-compose
artifact is now compatible with Kotlin Multiplatform, moving its code tocommon
and ships an Android artifact, matching the multiplatform support ofandroidx.compose
. The accommodate this change, the ComposableviewModel
method now accepts aKClass
in addition to ajava.lang.Class
. ( b/330323282 )
Исправления ошибок
- The
NullSafeMutableLiveData
has been refactored to avoid many false positives. ( I2d8c1 , Iafb18 , I03463 , I7ecef )
Dependency update
- The
lifecycle-viewmodel-compose
artifact now depends on Compose 1.6.0. - Lifecycle now depends on Profile Installer 1.3.1 .
Version 2.8.0-alpha03
20 марта 2024 г.
androidx.lifecycle:lifecycle-*:2.8.0-alpha03
is released. Version 2.8.0-alpha03 contains these commits .
Новые возможности
ViewModel.viewModelScope
is now an overridable constructor parameter, allowing you to inject your own dispatcher andSupervisorJob()
or to override the default by using thebackgroundScope
available withinrunTest
. ( 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 Multiplatform Compatibility
The lifecycle-viewmodel
artifact and APIs like ViewModel
, ViewModelStore
, ViewModelStoreOwner
, and ViewModelProvider
are now shipped in artifacts compatible with Kotlin Multiplatform. ( b/214568825 )
To accommodate this change, methods such as those on ViewModelProvider
that took a java.lang.Class<T>
now have an equivalent method that takes a kotlin.reflect.KClass<T>
.
Binary compatibility on Android has been maintained, but there are a few notable changes when comparing the Android API surface to the common API surface:
- Constructing a
ViewModelProvider
instance is now done through theViewModelProvider.create()
methods rather than directly calling its constructor. -
ViewModelProvider.NewInstanceFactory
andViewModelProvider.AndroidViewModelFactory
are only available on Android.- Custom Factories are recommended to extend from
ViewModelProvider.Factory
and use thecreate
method that takes aCreationExtras
or use theviewModelFactory
Kotlin DSL.
- Custom Factories are recommended to extend from
- Using
ViewModelProvider
without a custom factory on non-JVM platforms will result in anUnsupportedOperationException
. On JVM platforms, compatibility is preserved by using the no-args ViewModel constructor if a custom factory is not provided. -
viewModelScope
will fallback to anEmptyCoroutineContext
in platforms whereDispatchers.Main
is not available (eg, Linux).
Изменения поведения
-
InitializerViewModelFactory
(includingviewModelFactory
builder function) will now throw anIllegalArgumentException
if ainitializer
with the sameclazz: KClass<VM : ViewModel>
has already been added. ( Ic3a36 )
Исправления ошибок
-
ViewModel.getCloseable
now handles duplicated keys: if thekey
already has anAutoCloseable
resource associated with it, the old resource will be replaced and closed immediately. ( Ibeb67 ) - Accessing the
viewModelScope
of aViewModel
is now thread safe. ( If4766 , b/322407038 )
Внешний вклад
-
LocalLifecycleOwner
moved from Compose UI to lifecycle-runtime-compose so that its Compose-based helper APIs can be used outside of Compose UI. Thanks Jake Wharton for the contribution. ( I6c41b , b/328263448 )
Version 2.8.0-alpha02
21 февраля 2024 г.
androidx.lifecycle:lifecycle-*:2.8.0-alpha02
is released. Version 2.8.0-alpha02 contains these commits.
Новые возможности
- The
dropUnlessResumed
anddropUnlessStarted
APIs have been added which allow you to drop click or other events that occur even after theLifecycleOwner
has dropped below the givenLifecycle.State
. For example, this can be used with Navigation Compose to avoid handling click events after a transition to another screen has already begun:onClick: () -> Unit = dropUnlessResumed { navController.navigate(NEW_SCREEN) }
( Icba83 , b/317230685 )
Kotlin Conversions
-
ViewModel
is now written in Kotlin ( I16f26 , b/214568825 ) - The
lifecycle-viewmodel-ktx
kotlin extensions have now been moved to the base lifecycle module. ( Id787b , b/274800183 ) - The
lifecycle-runtime-ktx
kotlin extensions have now been moved to the base lifecycle module. ( Ic3686 , b/274800183 ) - The
lifecycle-livedata-core-ktx
kotlin extensions have now been moved to the base lifecycle module. ( I54a3d , b/274800183 )
Kotlin Multiplatform Compatibility
- The core Lifecycle APIs in
Lifecycle
,LifecycleOwner
,LifecycleObserver
,Lifecycle.State
,Lifecycle.Event
, andLifecycleRegistry
are now shipped in artifacts compatible with Kotlin Multiplatform. ( b/317249252 )
Изменения API
- Calling
LifecycleStartEffect
andLifecycleResumeEffect
without a key is now an error, following the same convention as theDisposableEffect
API that these APIs mirror. ( Ib0e0c , b/323518079 ) -
ViewModel
now usesAutoCloseable
instead ofCloseable
. That is a backward compatible change. ( I27f8e , b/214568825 ) - Deprecated
LiveDataReactiveStreams.toPublisher(lifecycleOwner, liveData)
in favor ofLiveData.toPublisher(lifecycleOwner)
. ( Iabe29 , b/262623005 )
Внешний вклад
- Thanks Ivan Matkov from Jetbrains for helping move Lifecycle to Kotlin Multiplatform. ( aosp/2926690 , I0c5ac , If445d )
Version 2.8.0-alpha01
24 января 2024 г.
androidx.lifecycle:lifecycle-*:2.8.0-alpha01
is released. Version 2.8.0-alpha01 contains these commits.
Новые возможности
-
ViewModel
now supports addingCloseable
objects with akey
that allows retrieving them viagetCloseable()
. ( I3cf63 )
Version 2.7
Version 2.7.0
10 января 2024 г.
androidx.lifecycle:lifecycle-*:2.7.0
is released. Version 2.7.0 contains these commits.
Important changes since 2.6.0
-
TestLifecycleOwner
now includes a suspending functionsetCurrentState()
which ensures that the state change and allLifecycleObserver
callbacks are completed before returning. Notably, unlike setting thecurrentState
property directly, this does not userunBlocking
, making it safe to use within a coroutine such as one provided byrunTest
. - The
LiveData
extensions ofmap
andswitchMap
now mirror the behavior ofdistinctUntilChanged
- if theLiveData
has avalue
set, themap
/switchMap
function will be immediately called to populate thevalue
of the returnedLiveData
. This ensures that the initial value will be set as part of the first composition (when used withobserveAsState()
), but does not change the observation behavior - updates values from the sourceLiveData
will still only apply once you start observing theLiveData
. - This release fixes an issue where
SavedStateHandle
would not properly restore customParcelable
classes 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
, andgetStateFlow
now specifically calls this limitation out. - The proguard keep rules associated with
LifecycleObserver
have been removed. This means that proguarded code that wishes to use APIs via reflection (such as using the long since deprecated@OnLifecycleEvent
annotation) 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 aFlow
ofLifecycle.Event
via theLifecycle.asFlow()
extension method. - Jetpack Compose users can now use
LifecycleEventEffect
to 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
LifecycleStartEffect
andLifecycleResumeEffect
to handle pairs of events - started to stopped and resumed to paused, respectively. This API mirrors the one found inDisposableEffect
and 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.State
can now be observed via theLifecycle.currentStateFlow
property, which returns aStateFlow
where thevalue
is the currentLifecycle.State
. - Jetpack Compose users can use the
Lifecycle.currentStateAsState()
extension to directly exposeLifecycle.State
as ComposeState
. This is equivalent (and a shorter alternative) tolifecycle.currentStateFlow.collectAsState()
.
See Collect lifecycle state with flows for more information.
Version 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
SavedStateHandle
would not properly restore customParcelable
classes 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
, andgetStateFlow
now specifically calls this limitation out. ( I0b55a )
Version 2.7.0-rc01
15 ноября 2023 г.
androidx.lifecycle:lifecycle-*:2.7.0-rc01
is released. Version 2.7.0-rc01 contains these commits.
Исправления ошибок
-
LifecycleStartEffect
andLifecycleResumeEffect
now correctly dispose and recreate the effect block if theLifecycleOwner
is changed. ( Ia25c6 )
Version 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.
Version 2.7.0-alpha03
18 октября 2023 г.
androidx.lifecycle:lifecycle-*:2.7.0-alpha03
is released. Version 2.7.0-alpha03 contains these commits.
Новые возможности
-
lifecycle-runtime-testing
now contains a new Lint check to avoid setting theLifecycle.State
of theTestLifecycleOwner
by using thecurrentState
field when inside of a coroutine. The Lint check now suggests the suspendingsetCurrentState
which allows setting theLifecycle.State
without blocking. ( Icf728 , b/297880630 )
Исправления ошибок
- Fixed an issue with
LiveData.switchMap
where returning the sameLiveData
instance both on the initial call and a subsequent call would prevent theLiveData
instance from being added as a source. ( Ibedcba7 )
Version 2.7.0-alpha02
6 сентября 2023 г.
androidx.lifecycle:lifecycle-*:2.7.0-alpha02
is released. Version 2.7.0-alpha02 contains these commits.
Новые возможности
-
TestLifecycleOwner
now includes the suspending functionsetCurrentState()
to give users the option of usingTestLifecycleOwner
from within a coroutine such as one provided byrunTest
. ( I329de , b/259344129 )
Изменения API
- All files from the
lifecycle-livedata-ktx
modules have been moved into the mainlifecycle-livedata
module. ( I10c6f , b/274800183 )
Изменения поведения
- The
LiveData.map()
andLiveData.switchMap()
extensions now sets thevalue
of the returnedLiveData
if the previousLiveData
has 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 theCloseable
if theViewModel
has already received a call toonCleared()
. ( I4712e , b/280294730 )
Исправления ошибок
- From Lifecycle
2.6.2
: Fixed an issue whereSavedStateHandle
would 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 betweenrememberSaveable
and Navigation Compose'sNavHost
. ( aosp/2729289 )
Version 2.7.0-alpha01
26 июля 2023 г.
androidx.lifecycle:lifecycle-*:2.7.0-alpha01
is released. Version 2.7.0-alpha01 contains these commits.
Изменения API
-
Lifecycle.State
is now Compose-observable viaLifecycle.currentStateFlow
, which returns aStateFlow
where thevalue
is the currentLifecycle.State
. ( Ib212d , b/209684871 ) -
Lifecycle.Event
s can now able to be observed as aFlow
withLifecycle.asFlow().
( If2c0f , b/176311030 ) -
LifecycleResumeEffect
API has been added to run ComposeSideEffect
s based on bothLifecycle.Event.ON_RESUME
andLifecycle.Event.ON_PAUSE
event callbacks. ( I60386 , b/235529345 ) -
LifecycleStartEffect
API has been added to run ComposeSideEffect
s based onLifecycle.Event.ON_START
andLifecycle.Event.ON_STOP
event callbacks. ( I5a8d1 , b/235529345 ) -
LifecycleEventEffect
API has been added to run ComposeSideEffect
s based onLifecycle.Event
. ( Ic9794 , b/235529345 ) -
Lifecycle.collectAsState()
extension has been added to directly exposeLifecycle.State
as ComposeState
. This is equivalent (and a shorter alternative) tolifecycle.currentStateFlow.collectAsState()
. ( I11015 , b/235529345 )
Исправления ошибок
- The
LiveData.distinctUntilChanged()
extension now sets thevalue
of the returnedLiveData
if the previousLiveData
has had a value set on it. This does not change the observation behavior - updated values from the sourceLiveData
will still only apply once you start observing theLiveData
returned fromdistinctUntilChanged()
. ( Ib482f ) - The proguard keep rules associated with
LifecycleObserver
have 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 )
Version 2.6
Version 2.6.2
6 сентября 2023 г.
androidx.lifecycle:lifecycle-*:2.6.2
is released. Version 2.6.2 contains these commits.
Исправления ошибок
- Fixed an issue where
SavedStateHandle
would 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 betweenrememberSaveable
and Navigation Compose'sNavHost
. ( aosp/2729289 )
Version 2.6.1
22 марта 2023 г.
androidx.lifecycle:lifecycle-*:2.6.1
is released. Version 2.6.1 contains these commits.
Обновления зависимостей
-
lifecycle-viewmodel-savedstate
now depends on SavedState1.2.1
. ( cd7251 ) - Lifecycle now depends on ProfileInstaller
1.3.0
. ( f9d30b )
Version 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
-
LiveData
now includes a newisInitialized
property that indicates whether an explicit value has ever been set on theLiveData
, allowing you to distinguish betweenliveData.value
returningnull
because no value has ever been set or an explicitnull
value. -
MediatorLiveData
now includes a constructor to set an initial value. - Added a new extension on
StateFlow
andFlow
ofcollectAsStateWithLifecycle()
that collect from flows and represents its latest value as Compose State in a lifecycle-aware manner. -
Lifecycle.launchWhenX
methods andLifecycle.whenX
methods 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
onChanged
method of aObserver
created in Kotlin now matches the nullability of the generic type. If you wantObserver.onChanged()
to accept a nullable type, you must instantiate theObserver
with 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
Version 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 thevalue
of the returnedLiveData
if the previousLiveData
has had a value set on it. This does not change the observation behavior - updated values from the sourceLiveData
will still only apply once you start observing theLiveData
returned fromdistinctUntilChanged()
. ( Ib482f )
Version 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
-
LifecycleOwner
is now written in Kotlin. This is a source incompatible change for classes written in Kotlin - they must now override thelifecycle
property rather than implementing the previousgetLifecycle()
function. ( I75b4b , b/240298691 ) -
ViewModelStoreOwner
is now in Kotlin. This is a source incompatible change for classes written in Kotlin - they must now override theviewModelStore
property rather than implementing the previousgetViewModelStore()
function. ( I86409 , b/240298691 ) - The Kotlin extension on
LifecycleOwner
that provides thelifecycleScope
field has been moved to thelifecycle-common
artifact fromlifecycle-runtime-ktx
. ( I41d78 , b/240298691 ) - The Kotlin extension on
Lifecycle
that provides thecoroutineScope
field has been moved to thelifecycle-common
artifact 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
-
Transformations
is 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.Function
method are deprecated and replaced with the versions that take a KotlinFunction1
. This change maintains binary compatibility. ( I8e14f ) -
ViewTreeViewModelStoreOwner
is 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 onView
ofandroidx.lifecycle.setViewTreeViewModelStoreOwner
andandroidx.lifecycle.findViewTreeViewModelStoreOwner
to 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
HasDefaultViewModelProviderFactory
interface is now written in Kotlin. This is a source incompatible change for classes written in Kotlin - they must now override thedefaultViewModelProviderFactory
anddefaultViewModelCreationExtras
properties rather than implementing the previous corresponding functions. ( Iaed9c , b/240298691 ) -
Observer
is now written in Kotlin. ItsonChanged()
method now uses the namevalue
for its parameter. ( Iffef2 , I4995e , b/240298691 ) -
AndroidViewModel
,AbstractSavedStateViewModelFactory
,LifecycleService
,ServiceLifecycleDispatcher
, andProcessLifecycleOwner
are 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.
Новые возможности
-
LiveData
now includes a newisInitialized
property that indicates whether an explicit value has ever been set on theLiveData
, allowing you to distinguish betweenliveData.value
returningnull
because no value has ever been set or an explicitnull
value. ( Ibd018 )
Изменения API
- The
collectAsStateWithLifecycle()
APIs oflifecycle-runtime-compose
are no longer in experimental status. ( I09d42 , b/258835424 ) -
Lifecycle.launchWhenX
methods andLifecycle.whenX
methods 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
-
ViewTreeLifecycleOwner
is 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 onView
ofandroidx.lifecycle.setViewTreeLifecycleOwner
andandroidx.lifecycle.findViewTreeLifecycleOwner
to 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 ) -
LiveDataReactiveStreams
is now written in Kotlin. The Kotlin extensions previously inlifecycle-reactivestreams-ktx
have been moved into thelifecycle-reactivestreams
module 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
, andViewModelStore
are now written in Kotlin ( Iadffd , ( I60034 , I8c52c , I9593d , I01fe1 , I59a23 , b/240298691 )
Исправления ошибок
-
SavedStateHandle
no longer crashes with aClassCastException
when callingget()
with the incorrect class type. ( I6ae7c )
Version 2.6.0-alpha03
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 )
Version 2.6.0-alpha02
7 сентября 2022 г.
androidx.lifecycle:lifecycle-*:2.6.0-alpha02
is released. Version 2.6.0-alpha02 contains these commits.
Изменения API
-
MediatorLiveData
now includes a constructor to set an initial value. ( Ib6cc5 , b/151244085 )
Исправления ошибок
-
Lifecycle
artifacts 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 acallbackFlow
rather than using its ownChannel
implementation to ensure thread-safety and context preservation. ( I4a8b2 , b/200596935 ) -
FlowLiveData
'sasLiveData
function will now preserve the initial value of aStateFlow
when creating the newLiveData
object. ( I3f530 , b/157380488 ) - From Lifecycle
2.5.1
: Custom implementations ofAndroidViewModelFactory
now correctly calls thecreate(modelClass)
function when using the stateful constructor withLifecycle
2.4+ ( I5b315 , b/238011621 )
Version 2.6.0-alpha01
29 июня 2022 г.
androidx.lifecycle:lifecycle-*:2.6.0-alpha01
is released. Version 2.6.0-alpha01 contains these commits.
Новые возможности
- Added a new extension on
StateFlow
andFlow
ofcollectAsStateWithLifecycle
that 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 )
Version 2.5
Version 2.5.1
27 июля 2022 г.
androidx.lifecycle:lifecycle-*:2.5.1
is released. Version 2.5.1 contains these commits.
Исправления ошибок
- Custom implementations of
AndroidViewModelFactory
now correctly call thecreate(modelClass)
function when using the statefulAndroidViewModelFactory
constructor withLifecycle
2.4+. ( I5b315 , b/238011621 )
Version 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
SavedStateHandle
now offers agetStateFlow()
API that returns a KotlinStateFlow
for monitoring value changes as an alternative to usingLiveData
.ViewModel CreationExtras - when writing a custom
ViewModelProvider.Factory
, it is no longer required to extendAndroidViewModelFactory
orAbstractSavedStateViewModelFactory
to gain access to anApplication
orSavedStateHandle
, respectively. Instead, these fields are provided to everyViewModelProvider.Factory
subclass asCreationExtras
via the new overload ofcreate
:create(Class<T>, CreationExtras)
. These extras are provided automatically by your Activity or Fragment when using Activity1.5.0
and 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-viewmodel
now provides aviewModelFactory
Kotlin DSL that allows you define yourViewModelProvider.Factory
in terms of one or more lambda initializers, one for each particularViewModel
class your custom factory supports, usingCreationExtras
as 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-compose
now offers aviewModel()
API that takes a lambda factory for creating aViewModel
instance 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-compose
artifact now contains new experimental APIs inSavedStateHandle.saveable
that allowrememberSaveable
like behavior backed by theSavedStateHandle
of 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 moreCloseable
objects to theViewModel
that will be closed when theViewModel
is 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
CoroutineScope
that 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
ViewModel
constructor 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 }
Behavior changes
- Attempting to move the
Lifecycle.State
fromINITIALIZED
toDESTROYED
will now always throw anIllegalStateException
regardless of whether theLifecycle
has an attached observer. -
LifecycleRegistry
will now clear their observers when they reach theDESTROYED
state.
Version 2.5.0-rc02
June 15, 2022
androidx.lifecycle:lifecycle-*:2.5.0-rc02
is released. Version 2.5.0-rc02 contains these commits.
Исправления ошибок
-
ViewModelProvider
will no longer crash when mixing previous versions of compileOnly Lifecycle dependencies with versions 2.5+. ( I81a66 , b/230454566 )
Version 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 aNullPointerException
when passed anull
source instead of propagating thenull
source to observers.( Ibd0fb , b/123085232 )
Version 2.5.0-beta01
April 20, 2022
androidx.lifecycle:lifecycle-*:2.5.0-beta01
is released. Version 2.5.0-beta01 contains these commits.
Изменения API
- Added
SavedStateHandle.saveable
property delegates to use property names as keys for persisting state into theSavedStateHandle
( I8bb86 , b/225014345 )
Исправления ошибок
- Fixed an issue where nesting one
NavHost
within anotherNavHost
in a non-primary bottom navigation tab would lead to anIllegalStateException
when 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
MutableState
overload toSavedStateHandle.saveable
for parity withrememberSaveable
( I38cfe , b/224565154 )
Изменения API
-
CreationExtras
is now abstract instead of sealed. ( Ib8a7a )
Исправления ошибок
- Fixed an
IllegalStateException: Already attached to lifecycleOwner
error 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-compose
module now providesSavedStateHandleSaver
, an experimental API that ensures values in aSavedStateHandle
are integrated correctly with the same saved instance state thatrememberSaveable
uses. ( Ia88b7 , b/195689777 )
Изменения API
- Fixed a compatibility issue with Lifecycle 2.3 and newer Lifecycle versions in Java. ( I52c8a , b/219545060 )
Исправления ошибок
-
SavedStateViewFactory
now supports usingCreationExtras
even 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
-
SavedStateHandle
now offers agetStateFlow()
API that returns a KotlinStateFlow
for monitoring value changes as an alternative to usingLiveData
. ( Iad3ab , b/178037961 )
Version 2.5.0-alpha03
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 moreCloseable
objects to theViewModel
that will be closed when theViewModel
is cleared without requiring any manual work inonCleared()
. ( I55ea0 ) -
lifecycle-viewmodel
now provides anInitializerViewModelFactory
that allows you to add lambda for handling particularViewModel
classes, usingCreationExtras
as the primary data source. ( If58fc , b/216687549 ) -
lifecycle-viewmodel-compose
now offers aviewModel()
API that takes a lambda factory for creating aViewModel
instance without requiring the creation of a customViewModelProvider.Factory
. ( I97fbb , b/216688927 )
Изменения API
- You can now create a
ViewModel
withCreationExtras
vialifecycle-viewmodel-compose
. ( I08887 , b/216688927 )
Behavior changes
- Attempting to move the
Lifecycle.State
fromINITIALIZED
toDESTROYED
will now always throw anIllegalStateException
regardless of whether theLifecycle
has an attached observer. ( I7c390 , b/177924329 ) -
LifecycleRegistry
will now clear their observers when they reach theDESTROYED
state. ( I4f8dd , b/142925860 )
Version 2.5.0-alpha02
9 февраля 2022 г.
androidx.lifecycle:lifecycle-*:2.5.0-alpha02
is released. Version 2.5.0-alpha02 contains these commits.
Изменения API
-
SavedStateHandle
andSavedStateViewModelFactory
have been converted to Kotlin. This has improved the nullability of the generics in both classes. ( Ib6ce2 , b/216168263 , I9647a , b/177667711 ) - The
LiveData
switchMap
function parameter can now have a nullable output. ( I40396 , b/132923666 ) - The
LiveData
-ktx extensions are now annotated with@CheckResult
to enforce that the result is used when calling these functions. ( Ia0f05 , b/207325134 )
Behavior changes
-
SavedStateHandle
now properly stores the defaultValue when no value for the specified key exists. ( I1c6ce , b/178510877 )
Исправления ошибок
- From Lifecycle
2.4.1
: Updatedlifecycle-process
to depend on Startup 1.1.1 to ensure that fixes that preventProcessLifecycleInitializer
from throwing aStartupException
are available by default. ( Ib01df , b/216490724 ) - There is now an improved error message when custom
AndroidViewModel
classes have parameters in the wrong order and attempt to create aViewModel
. ( I340f7 , b/177667711 ) - You can now create a view model via
CreationExtras
using theAndroidViewModelFactory
without setting an application. ( I6ebef , b/217271656 )
Version 2.5.0-alpha01
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
: thisString
provides access to the custom key you passed toViewModelProvider.get()
. -
ViewModelProvider.AndroidViewModelFactory.APPLICATION_KEY
provides access to theApplication
class. -
SavedStateHandleSupport.SAVED_STATE_REGISTRY_OWNER_KEY
provides access to theSavedStateRegistryOwner
that is being used to construct this ViewModel. -
SavedStateHandleSupport.VIEW_MODEL_STORE_OWNER_KEY
provides access to theViewModelStoreOwner
that is being used to construct this ViewModel. -
SavedStateHandleSupport.DEFAULT_ARGS_KEY
provides access to theBundle
of 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 идем вперед.
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
SavedStateHandle
would reappear after process death and recreation, even if it was specifically removed from theSavedStateHandle
. As a consequence of this,SavedStateHandle
will no longer merge default values and restored values together, instead only using the restored values as the source of truth. ( I53a4b )
Version 2.4
Version 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 aSavedStateHandle
would re-appear after process death and recreation, even if it was specifically removed from theSavedStateHandle
. As a consequence of this,SavedStateHandle
will no longer merge default values and restored values together, instead only using the restored values as the source of truth. ( I53a4b ) -
lifecycle-process
now depends on Androidx Startup 1.1.1 which fixed a regression in where usingProcessLifecycleInitializer
would cause anStartupException
. ( b/216490724 )
Version 2.4.0
27 октября 2021 г.
androidx.lifecycle:lifecycle-*:2.4.0
is released. Version 2.4.0 contains these commits.
Important changes since 2.3.0
-
@OnLifecycleEvent
was deprecated.LifecycleEventObserver
orDefaultLifecycleObserver
should be used instead. -
androidx.lifecycle:lifecycle-viewmodel-compose
library was added. It providesviewModel()
composable andLocalViewModelStoreOwner
.- Source-breaking change :
ViewModelProvider
has been rewritten in Kotlin.ViewModelProvider.Factory.create
method 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. -
DefaultLifecycleObserver
was moved fromlifecycle.lifecycle-common-java8
tolifecycle.lifecycle-common
.lifecycle.lifecycle-common-java8
doesn'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-ktx
have been moved to thelifecycle-viewmodel
module. lifecycle-process
now usesandroidx.startup
to initialize theProcessLifecycleOwner
.Previously, this was being done by
androidx.lifecycle.ProcessLifecycleOwnerInitializer
.If you used
tools:node="remove"
theContentProvider
being 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>
Version 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.
Version 2.4.0-beta01
September 15, 2021
androidx.lifecycle:lifecycle-*:2.4.0-beta01
is released. Version 2.4.0-beta01 contains these commits.
Изменения API
-
@OnLifecycleEvent
was deprecated.LifecycleEventObserver
orDefaultLifecycleObserver
should be used instead. ( I5a8fa ) - DefaultLifecycleObserver was moved from
androidx.lifecycle.lifecycle-common-java8
toandroidx.lifecycle.lifecycle-common
.androidx.lifecycle.lifecycle-common-java8
doesn'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-ktx
have been moved to thelifecycle-viewmodel
module. ( I6d5b2 )
Внешний вклад
Version 2.4.0-alpha03
August 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.create
method no longer allows nullable generic. ( I9b9f6 )
Изменения поведения
- The
Lifecycle.repeatOnLifecycle
:block
is now always invoked serially when repeating execution. ( Ibab33 )
Внешний вклад
- Thanks chao2zhang for fixing the code snippets in the
repeatOnLifecycle
documentation. #205 .
Version 2.4.0-alpha02
16 июня 2021 г.
androidx.lifecycle:lifecycle-*:2.4.0-alpha02
is released. Version 2.4.0-alpha02 contains these commits.
Новые возможности
- Added a new
RepeatOnLifecycleWrongUsage
lint check tolifecycle-runtime-ktx
that detects whenrepeateOnLifecycle
is incorrectly used inonStart()
oronResume()
. ( 706078 , b/187887400 )
Изменения API
- The
LifecycleOwner.addRepeatingJob
API is removed in favor ofLifecycle.repeatOnLifecycle
that respects structured concurrency and is easier to reason about. ( I4a3a8 ) - Make
ProcessLifecycleInitializer
public so otherandroidx.startup.Initializer
s can use these as dependencies. ( I94c31 )
Исправления ошибок
- Fixed an issue with the
NullSafeMutableLiveData
lint check when the field has modifiers. ( #147 , b/183696616 ) - Fixed another issue with the
NullSafeMutableLiveData
lint check when using generics. ( #161 , b/184830263 )
Внешний вклад
- Thanks maxsav for improving the
NullSafeMutableLiveData
lint check. ( #147 , b/183696616 ) - Thanks kozaxinan for improving the
NullSafeMutableLiveData
lint check. ( #161 , b/184830263 )
Version 2.4.0-alpha01
24 марта 2021 г.
androidx.lifecycle:lifecycle-*:2.4.0-alpha01
is released. Version 2.4.0-alpha01 contains these commits.
Изменения поведения
lifecycle-process
now usesandroidx.startup
to initialize theProcessLifecycleOwner
.Previously, this was being done by
androidx.lifecycle.ProcessLifecycleOwnerInitializer
.If you used
tools:node="remove"
theContentProvider
being 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.flowWithLifecycle
API that emits values from the upstream Flow when the lifecycle is at least in a certain state using theLifecycle.repeatOnLifecycle
API. This is an alternative to the also newLifecycleOwner.addRepeatinJob
API. ( I0f4cd )
Исправления ошибок
- From Lifecycle 2.3.1 : The
NonNullableMutableLiveData
lint 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.
Breaking API Changes
-
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
June 2, 2021
androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha06
is released. Версия 1.0.0-alpha06 содержит эти коммиты.
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. Версия 1.0.0-alpha05 содержит эти коммиты.
Новые возможности
- 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
April 7, 2021
androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha04
is released. Версия 1.0.0-alpha04 содержит эти коммиты.
Dependency Changes
- This version allows
androidx.hilt:hilt-navigation-compose
andandroidx.navigation:navigation-compose
to sync dependencies onandroidx.compose.compiler:compiler:1.0.0-beta04
andandroidx.compose.runtime:runtime:1.0.0-beta04
. For 1.0.0, it is required that the compiler and runtime match.
Версия 1.0.0-альфа03
March 10, 2021
androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha03
is released. Версия 1.0.0-alpha03 содержит эти коммиты.
Изменения API
-
LocalViewModelStoreOwner.current
now returns a nullableViewModelStoreOwner
to better determine whether aViewModelStoreOwner
is available in the current composition. APIs that require aViewModelStoreOwner
, such asviewModel()
andNavHost
, still throw an exception if aViewModelStoreOwner
is not set. ( Idf39a )
Lifecycle-Viewmodel-Compose Version 1.0.0-alpha02
24 февраля 2021 г.
androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha02
is released. Версия 1.0.0-alpha02 содержит эти коммиты.
Изменения API
-
LocalViewModelStoreOwner
now has aprovides
functions 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. Версия 1.0.0-alpha01 содержит эти коммиты.
Новые возможности
- The
viewModel()
composable andLocalViewModelStoreOwner
were moved fromandroidx.compose.ui.viewinterop
to this artifact in theandroidx.lifecycle.viewmodel.compose
package. ( I7a374 )
Version 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
NonNullableMutableLiveData
lint rule can now properly differentiate between field variables with different nullability. ( b/169249668 )
Version 2.3.0
Version 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
-
SavedStateHandle
support for non-parcelable classes :SavedStateHandle
now supports lazy serialization by allowing you to callsetSavedStateProvider()
for a given key, providing aSavedStateProvider
that will get a callback tosaveState()
when theSavedStateHandle
is asked to save its state. See Saving non-parcelable classes . - Lifecycle Behavior Enforcement :
- LifecycleRegistry now enforces
DESTROYED
as a terminal state. -
LifecycleRegistry
now 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. ForLifecycleRegistry
objects 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 thisLifecycleRegistry
is 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.Event
for generating theEvent
given aState
and transition direction. Added thegetTargetState()
method that provides theState
that the Lifecycle will transition to directly following theEvent
. -
withStateAtLeast
: AddedLifecycle.withStateAtLeast
APIs 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 ) -
ViewTree
APIs : A newViewTreeLifecycleOwner.get(View)
andViewTreeViewModelStoreOwner.get(View)
API allows you to retrieve the containingLifecycleOwner
andViewModelStoreOwner
, respectively, given aView
instance. You must upgrade to Activity1.2.0
and Fragment1.3.0
, and AppCompat 1.3.0-alpha01 or higher to populate this correctly. ThefindViewTreeLifecycleOwner
andfindViewTreeViewModelStoreOwner
Kotlin extensions are available inlifecycle-runtime-ktx
andlifecycle-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.
Version 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 ofSavedStateHandle
is 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 )
Version 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 )
Documentation Changes
- The
liveData
builder 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
NullSafeMutableLiveData
Lint 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.Event
for generating theEvent
given aState
and transition direction. Added thegetTargetState()
method that provides theState
that the Lifecycle will transition to directly following theEvent
. ( I00887 ) - Added
Lifecycle.withStateAtLeast
APIs 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
DESTROYED
as a terminal state. ( I00887 ) -
LifecycleRegistry
now 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. ForLifecycleRegistry
objects 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 thisLifecycleRegistry
is accessed from different threads ( Ie7280 , b/137392809 )
Исправления ошибок
- Fixed a crash in
NullSafeMutableLiveData
. ( b/159987480 ) - Fixed an
ObsoleteLintCustomCheck
for 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.
Исправления ошибок
-
LiveData
now 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 )
Version 2.3.0-alpha04
10 июня 2020 г.
androidx.lifecycle:lifecycle-*:2.3.0-alpha04
is released. Version 2.3.0-alpha04 contains these commits.
Исправления ошибок
- Fixed a crash in the
NonNullableMutableLiveData
Lint check. ( b/157294666 ) - The
NonNullableMutableLiveData
Lint check now covers significantly more cases where anull
value was set on aMutableLiveData
with a non-null type parameter. ( b/156002218 )
Version 2.3.0-alpha03
May 20, 2020
androidx.lifecycle:lifecycle-*:2.3.0-alpha03
are released. Version 2.3.0-alpha03 contains these commits.
Новые возможности
-
SavedStateHandle
now supports lazy serialization by allowing you to callsetSavedStateProvider()
for a given key, providing aSavedStateProvider
that will get a callback tosaveState()
when theSavedStateHandle
is asked to save its state. ( b/155106862 ) - A new
ViewTreeViewModelStoreOwner.get(View)
API allows you to retrieve the containingViewModelStoreOwner
given aView
instance. You must upgrade to Activity1.2.0-alpha05
, Fragment1.3.0-alpha05
, and AppCompat1.3.0-alpha01
to populate this correctly. AfindViewModelStoreOwner()
Kotlin extension has been added tolifecycle-viewmodel-ktx
. ( aosp/1295522 )
Исправления ошибок
- Fixed an issue that caused the
MutableLiveData
Lint checks released in Lifecycle2.3.0-alpha01
from being published alongside thelifecycle-livedata-core-ktx
artifact. ( b/155323109 )
Version 2.3.0-alpha02
29 апреля 2020 г.
androidx.lifecycle:lifecycle-*:2.3.0-alpha02
is released. Version 2.3.0-alpha02 contains these commits.
Изменения API
-
SavedStateViewModelFactory
now allows you to pass a nullApplication
to its constructor to better support cases where one is not readily available and support forAndroidViewModel
is not needed. ( aosp/1285740 )
Исправления ошибок
- Improved cold start performance by avoiding class verification failure on API 28 and lower devices. ( aosp/1282118 )
Version 2.3.0-alpha01
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 containingLifecycleOwner
given aView
instance. You must upgrade to Activity1.2.0-alpha01
and Fragment1.3.0-alpha01
to populate this correctly. AfindViewTreeLifecycleOwner
Kotlin extension is available inlifecycle-runtime-ktx
. ( aosp/1182361 , aosp/1182956 ) - Added a new Lint check that warns you when setting a
null
value on aMutableLiveData
that has been defined in Kotlin as non-null. This is available when using thelivedata-core-ktx
orlivedata-ktx
artifacts. ( aosp/1154723 , aosp/1159092 ) - A new
lifecycle-runtime-testing
artifact is available that provides aTestLifecycleOwner
that implementsLifecycleOwner
and provides a thread safe mutableLifecycle
. ( aosp/1242438 )
Исправления ошибок
- The
lifecycle-runtime
artifact now has a unique package name. ( aosp/1187196 )
Version 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
.
Version 2.2.0
January 22, 2020
androidx.lifecycle:lifecycle-*:2.2.0
is released. Version 2.2.0 contains these commits .
Important changes since 2.1.0
- Lifecycle Coroutine Integration : The new
lifecycle-runtime-ktx
artifact adds integration between Lifecycle and Kotlin coroutines. Thelifecycle-livedata-ktx
has 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 aFragment
orFragmentActivity
to the newViewModelProvider(ViewModelStoreOwner)
constructor to achieve the same functionality when using Fragment1.2.0
. -
lifecycle-extensions
Artifact Deprecation : With the above deprecation ofViewModelProviders.of()
, this release marks the deprecation of the last API inlifecycle-extensions
and this artifact should now be considered deprecated in its entirety. We strongly recommend depending on the specific Lifecycle artifacts you need (such aslifecycle-service
if you're usingLifecycleService
andlifecycle-process
if you're usingProcessLifecycleOwner
) rather thanlifecycle-extensions
as there will not be a future2.3.0
release 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
DefautLifecycleObserver
instead; 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
ViewModel
was stored inViewModelStore
and queried later with default factory. - Fix a usage of
Dispatchers.Main.immediate
inlaunchWhenCreated
and similar methods to be called synchronously during corresponding lifecycle event. ( aosp/1156203 )
External contributions
- 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 )
Version 2.2.0-rc01
October 23, 2019
androidx.lifecycle:lifecycle-*:2.2.0-rc01
is released. Version 2.2.0-rc01 contains these commits .
Исправления ошибок
- Fixed an issue where
launchWhenCreated
and related methods would run one frame later than the associated lifecycle method due to its use ofDispatchers.Main
instead ofDispatchers.Main.immediate
. ( aosp/1145596 )
External contributions
- Thanks to Nicklas Ansman for contributing the fix! ( aosp/1145596 )
Version 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
ProcessLifecycleOwner
and the activity'sLifecycleOwner
moving to started and resumed on Android 10 devices. ( aosp/1128132 ) - Fixed a regression introduced in Lifecycle
2.2.0-alpha05
which would cause aNullPointerException
when using version2.0.0
or2.1.0
oflifecycle-process
. ( b/141536990 )
Version 2.2.0-alpha05
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 ofliveData
now useDispatchers.Main.immediate
instead ofDispatchers.Main
. ( b/139740492 )
External contributions
- 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
ViewModelStoreOwner
can now optionally implementHasDefaultViewModelProviderFactory
to 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 aFragment
orFragmentActivity
to the newViewModelProvider(ViewModelStoreOwner)
constructor to achieve the same functionality. ( aosp/1009889 )
Version 2.2.0-alpha02
2 июля 2019 г.
androidx.lifecycle:*:2.2.0-alpha02
is released. The commits included in this version can be found here .
Изменения API
- Replaced
LiveDataScope.initialValue
withLiveDataScope.latestValue
which will track the current emitted value of theliveData
block. - Added a new overload to the
liveData
builder that receivestimeout
parameter as typeDuration
Version 2.2.0-alpha01
May 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
Version 1.0.0
January 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
ViewModel
classes to access and to contribute to the saved state. This object can be received in constructor ofViewModel
class and factories provided by default by Fragments and AppCompatActivity will injectSavedStateHandle
automatically. - AbstractSavedStateViewModelFactory was added. It allows you to create custom factories for your
ViewModel
and 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
October 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
IllegalStateException
when usingAbstractSavedStateViewModelFactory
. ( b/141225984 )
ViewModel-SavedState Version 1.0.0-alpha05
18 сентября 2019 г.
androidx.lifecycle:lifecycle-viewmodel-savedstate:1.0.0-alpha05
is released. Версия 1.0.0-alpha05 содержит эти коммиты .
Изменения API
-
SavedStateViewModelFactory
no longer extendsAbstractSavedStateViewModelFactory
andSavedStateHandle
is 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-savedstate
no longer depends onfragment
and the relatedSavedStateViewModelFactory(Fragment)
andSavedStateViewModelFactory(FragmentActivity)
constructors have been removed. Instead,SavedStateViewModelFactory
is 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
-
SavedStateVMFactory
is renamed toSavedStateViewModelFactory
. -
AbstractSavedStateVMFactory
is 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
ViewModels
can contribute to savedstate. To do that you use newly introduced viewmodel's factorySavedStateVMFactory
and your ViewModel should have a constructor that receivesSavedStateHandle
object as a parameter.
Version 2.1.0
Important changes since 2.0.0
- Added
LifecycleEventObserver
for the cases when a stream of lifecycle events is needed. It is a public API instead of a hiddenGenericLifecycleObserver
class. - Added ktx extensions for
LiveData.observe
methods andTransformations.*
methods. - Added
Transformations.distinctUntilChanged
, which creates a new LiveData object that does not emit a value until the sourceLiveData
value has been changed. - Added coroutine support in ViewModels by adding the extension property
ViewModel.viewModelScope
.
Version 2.1.0
5 сентября 2019 г.
androidx.lifecycle:lifecycle-*:2.1.0
is released. The commits included in this version can be found here .
Version 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 .
Version 2.1.0-beta01
May 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
liveData
extension functions for transformations and observations,ViewModel
initialisation with property delegation and others are stabilised and not going to change.
Version 2.1.0-alpha04
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 aViewModelStore
directly, rather than only aViewModelStoreOwner
. ( aosp/932932 )
Version 2.1.0-alpha03
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.KeyedFactory
was removed. Second interface in addition toViewModelProvider.Factory
didn't compose well with new features as property delegation in Kotlinby viewmodels {}
. ( aosp/914133 )
Version 2.1.0-alpha02
January 30, 2019
androidx.lifecycle 2.1.0-alpha02
is released.
Изменения API
-
LifecycleRegistry
now contains asetCurrentState()
method that replaces the now deprecatedsetState()
method. ( aosp/880715 )
Исправления ошибок
- Fixed an issue where mock
ViewModel
instances would crash when the containingViewModelStore
was cleared. b/122273087
Version 2.1.0-alpha01
December 17, 2018
androidx.lifecycle 2.1.0-alpha01
is released.
Новые возможности
- Added
LifecycleEventObserver
for the cases when a stream of lifecycle events is needed. It is a public api instead of a hiddenGenericLifecycleObserver
class. - Added ktx extensions for
LiveData.observe
methods andTransformations.*
methods. - Method
Transformations.distinctUntilChanged
was added. It creates a newLiveData
object that does not emit a value until the source LiveData value has been changed. - Coroutine support in ViewModels: extension property
ViewModel.viewModelScope
was added. - Added
ViewModelProvider.KeyedFactory
, a factory for ViewModels that receiveskey
andClass
increate
method.
Version 2.0.0
Version 2.0.0
September 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
Version 2.0.0-beta01
July 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
March 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 г.
Packaging Changes
New, much smaller dependencies are now available:
-
android.arch.lifecycle:livedata:1.1.0
-
android.arch.lifecycle:viewmodel:1.1.0
Изменения API
- The deprecated
LifecycleActivity
andLifecycleFragment
have now been removed - please useFragmentActivity
,AppCompatActivity
or supportFragment
. -
@NonNull
annotations have been added toViewModelProviders
andViewModelStores
-
ViewModelProviders
constructor has been deprecated - please use its static methods directly -
ViewModelProviders.DefaultFactory
has been deprecated - please useViewModelProvider.AndroidViewModelFactory
- The static
ViewModelProvider.AndroidViewModelFactory.getInstance(Application)
method has been added to retrieve a staticFactory
suitable for creatingViewModel
andAndroidViewModel
instances.