十二、Jetpack
1.ViewModel
ViewModel 的一个重要作用就是可以帮助 Activity 分担一部分工作,它是专门用于存放与界面相关的数据。也就是说,只要是界面上能看得到的数据,它的相关变量都应该存放在 ViewModel 中,而不是 Activity 中,这样可以在一定程度上减少 Activity 中的逻辑。另外,ViewModel 还有一个非常重要的特性。我们都知道,当手机发生横竖屏旋转的时候,Activity 会被重新创建,同时存放在 Activity 中的数据也会丢失。而 ViewModel 的生命周期和 Activity 不同,它可以保证在手机屏幕发生旋转的时候不会被重新创建,只有当 Activity 退出的时候才会跟着 Activity 一起销毁。因此,将与界面相关的变量存放到 ViewModel 中,这样即使旋转手机屏幕,界面上显示的数据也不会丢失。
ViewModel 的基本用法
//build.gradle
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
//MainViewModel.kt
package com.tomorrow.kotlindemo
import androidx.lifecycle.ViewModel
class MainViewModel : ViewModel() {
var counter = 0
}
//MainActivity.kt
package com.tomorrow.kotlindemo
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProviders
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
lateinit var viewModel: MainViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
button.setOnClickListener {
viewModel.counter++
refreshContent()
}
}
private fun refreshContent() {
textView.text = viewModel.counter.toString()
}
}
向 ViewModel 传递参数
//build.gradle
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
//MainViewModel.kt
package com.tomorrow.kotlindemo
import androidx.lifecycle.ViewModel
class MainViewModel(countReserved: Int) : ViewModel() {
var counter = countReserved
}
//MainViewModelFactory.kt
package com.tomorrow.kotlindemo
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
class MainViewModelFactory(private val countReserved: Int) : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return MainViewModel(countReserved) as T
}
}
//MainActivity.kt
package com.tomorrow.kotlindemo
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProviders
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
lateinit var viewModel: MainViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val countReserved = 5
viewModel = ViewModelProviders.of(this, MainViewModelFactory(countReserved)).get(MainViewModel::class.java)
button.setOnClickListener {
viewModel.counter++
refreshContent()
}
}
private fun refreshContent() {
textView.text = viewModel.counter.toString()
}
}
2.Lifecycles
感知 Activity 或 Fragment 的生命周期。
//MyObserver.kt
package com.tomorrow.kotlindemo
import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
class MyObserver : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun activityStart() {
Log.d("TAG", "zwm, activityStart")
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun activityStop() {
Log.d("TAG", "zwm, activityStop")
}
}
//MainActivity.kt
package com.tomorrow.kotlindemo
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
lifecycle.addObserver(MyObserver())
}
}
只要你的 Activity 是继承自 AppCompatActivity 的,或者你的 Fragment 是继承自 androidx.fragment.app.Fragment 的,那么它们本身就是一个 LifecycleOwner 的实例,这部分工作已经由 AndroidX 库自动帮我们完成了。
主动获取当前的生命周期状态:
//MyObserver.kt
class MyObserver(private val lifecycle: Lifecycle) : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun activityStart() {
Log.d("TAG", "zwm, activityStart")
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun activityStop() {
Log.d("TAG", "zwm, activityStop")
}
fun method() {
if (lifecycle.currentState == Lifecycle.State.RESUMED) {
//TODO
}
}
}
3.LiveData
LiveData 是 Jetpack 提供的一种响应式编程组件,它可以包含任何类型的数据,并在数据发生变化的时候通知给观察者。LiveData 特别适合与 ViewModel 结合在一起使用,虽然它也可以单独用在别的地方,但是在绝大多数情况下,它是使用在 ViewModel 当中的。
LiveData 的基本用法
//build.gradle
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
//MainViewModel.kt
package com.tomorrow.kotlindemo
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class MainViewModel(countReserved: Int) : ViewModel() {
var counter = MutableLiveData<Int>()
init {
counter.value = countReserved
}
fun plusOne() {
val count = counter.value ?: 0
counter.value = count + 1
}
}
//MainViewModelFactory.kt
package com.tomorrow.kotlindemo
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
class MainViewModelFactory(private val countReserved: Int) : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return MainViewModel(countReserved) as T
}
}
//MainActivity.kt
package com.tomorrow.kotlindemo
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
lateinit var viewModel: MainViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val countReserved = 5
viewModel = ViewModelProviders.of(this, MainViewModelFactory(countReserved)).get(MainViewModel::class.java)
viewModel.counter.observe(this, Observer { count ->
textView.text = count.toString()
}) //此处没有使用 Java 函数式 API
button.setOnClickListener {
viewModel.plusOne()
}
}
}
MutableLiveData 是一种可变的 LiveData,它的用法很简单,主要有 3 种读写数据的方法,分别是 getValue()、setValue() 和 postValue() 方法。getValue() 方法用于获取 LiveData 中包含的数据;setValue() 方法用于给 LiveData 设置数据,但是只能在主线程中调用;postValue() 方法用于在非主线程中给 LiveData 设置数据。
因为 observe() 方法接收的另一个参数 LifecycleOwner 也是一个单抽象方法接口,当一个 Java 方法同时接收两个单抽象方法接口参数时,要么同时使用函数式 API 的写法,要么都不使用函数式 API 的写法,由于第一个参数传的是 this,因此第二个参数就无法使用函数式 API 的写法了。
比较推荐的做法是,永远只暴露不可变的 LiveData 给外部,这样在非 ViewModel 中就只能观察 LiveData 的数据变化,而不能给 LiveData 设置数据:
class MainViewModel(countReserved: Int) : ViewModel() {
val counter : LiveData<Int>
get() = _counter
private var _counter = MutableLiveData<Int>()
init {
_counter.value = countReserved
}
fun plusOne() {
val count = _counter.value ?: 0
_counter.value = count + 1
}
}
map 和 switchMap
map() 方法的作用是将实际包含数据的 LiveData 和仅用于观察数据的 LiveData 进行转换:
//User.kt
package com.tomorrow.kotlindemo
data class User(var firstName: String, var lastName: String, var age: Int)
//MainViewModel.kt
package com.tomorrow.kotlindemo
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
class MainViewModel : ViewModel() {
private val userLiveData = MutableLiveData<User>()
val userName: LiveData<String> = Transformations.map(userLiveData) { user ->
Log.d("TAG", "zwm, Transformations map")
"${user.firstName} ${user.lastName}"
}
fun getUserName() {
Log.d("TAG", "zwm, getUserName")
userLiveData.value = User("First", "Last", 10)
}
}
//MainActivity.kt
package com.tomorrow.kotlindemo
import android.os.Bundle
import android.os.Handler
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
class MainActivity : AppCompatActivity() {
lateinit var viewModel: MainViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
viewModel.userName.observe(this, Observer { userName ->
Log.d("TAG", "zwm, userName: $userName")
})
Handler().postDelayed({
viewModel.getUserName()
}, 3000)
}
}
日志打印:
2020-10-29 19:25:25.407 6644-6644/com.tomorrow.kotlindemo D/TAG: zwm, getUserName
2020-10-29 19:25:25.408 6644-6644/com.tomorrow.kotlindemo D/TAG: zwm, Transformations map
2020-10-29 19:25:25.409 6644-6644/com.tomorrow.kotlindemo D/TAG: zwm, userName: First Last
假设 ViewModel 中的某个 LiveData 对象不是在 ViewModel 中创建的,而是调用另外的方法获取的,我们可以借助 switchMap() 方法将这个 LiveData 对象转换成另外一个可观察的 LiveData 对象:
//User.kt
package com.tomorrow.kotlindemo
data class User(var firstName: String, var lastName: String, var age: Int)
//Repository.kt
package com.tomorrow.kotlindemo
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
object Repository {
fun getUser(userId: String) : LiveData<User> {
val liveData = MutableLiveData<User>()
liveData.value = User("ID: ", userId, 12)
return liveData
}
}
//MainViewModel.kt
package com.tomorrow.kotlindemo
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
class MainViewModel : ViewModel() {
private val userIdLiveData = MutableLiveData<String>()
val user: LiveData<User> = Transformations.switchMap(userIdLiveData) { userId ->
Log.d("TAG", "zwm, Transformations switchMap")
Repository.getUser(userId)
}
fun getUserName(userId: String) {
Log.d("TAG", "zwm, getUserName")
userIdLiveData.value = userId
}
}
//MainActivity.kt
package com.tomorrow.kotlindemo
import android.os.Bundle
import android.os.Handler
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
class MainActivity : AppCompatActivity() {
lateinit var viewModel: MainViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
viewModel.user.observe(this, Observer { user ->
Log.d("TAG", "zwm, user: ${user.firstName} ${user.lastName}")
})
Handler().postDelayed({
viewModel.getUserName("10086")
}, 3000)
}
}
日志打印:
2020-10-29 20:03:22.943 10015-10015/com.tomorrow.kotlindemo D/TAG: zwm, getUserName
2020-10-29 20:03:22.944 10015-10015/com.tomorrow.kotlindemo D/TAG: zwm, Transformations switchMap
2020-10-29 20:03:22.946 10015-10015/com.tomorrow.kotlindemo D/TAG: zwm, user: ID: 10086
假设 ViewModel 中某个获取数据的方法没有参数,即在没有可观察数据的情况下,写法如下:
//User.kt
package com.tomorrow.kotlindemo
data class User(var firstName: String, var lastName: String, var age: Int)
//Repository.kt
package com.tomorrow.kotlindemo
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
object Repository {
fun getUser() : LiveData<User> {
val liveData = MutableLiveData<User>()
liveData.value = User("First", "Last", 12)
return liveData
}
}
//MainViewModel.kt
package com.tomorrow.kotlindemo
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
class MainViewModel : ViewModel() {
private val userIdLiveData = MutableLiveData<String>()
val user: LiveData<User> = Transformations.switchMap(userIdLiveData) { userId ->
Log.d("TAG", "zwm, Transformations switchMap")
Repository.getUser()
}
fun getUserName() {
Log.d("TAG", "zwm, getUserName")
userIdLiveData.value = userIdLiveData.value
}
}
//MainActivity.kt
package com.tomorrow.kotlindemo
import android.os.Bundle
import android.os.Handler
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
class MainActivity : AppCompatActivity() {
lateinit var viewModel: MainViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
viewModel.user.observe(this, Observer { user ->
Log.d("TAG", "zwm, user: ${user.firstName} ${user.lastName}")
})
Handler().postDelayed({
viewModel.getUserName()
}, 3000)
}
}
日志打印:
2020-10-29 19:58:40.482 9560-9560/com.tomorrow.kotlindemo D/TAG: zwm, getUserName
2020-10-29 19:58:40.482 9560-9560/com.tomorrow.kotlindemo D/TAG: zwm, Transformations switchMap
2020-10-29 19:58:40.483 9560-9560/com.tomorrow.kotlindemo D/TAG: zwm, user: First Last
LiveData 内部不会判断即将设置的数据和原有数据是否相同,只要调用了 setValue() 或 postValue() 方法,就一定会触发数据变化事件。
LiveData 之所以能够成为 Activity 与 ViewModel 之间通信的桥梁,并且还不会有内存泄露的风险,靠的就是 Lifecycles 组件。LiveData 在内部使用了 Lifecycles 组件来自我感知生命周期的变化,从而可以在 Activity 销毁的时候及时释放引用,避免产生内存泄露的问题。另外,由于要减少性能消耗,当 Activity 处于不可见状态的时候(比如手机息屏,或者被其他的 Activity 遮挡),如果 LiveData 中的数据发生了变化,是不会通知给观察者的。只有当 Activity 重新恢复可见状态时,才会将数据通知给观察者,而 LiveData 之所以能够实现这种细节的优化,依靠的还是 Lifecycles 组件。还有一个小细节,如果在 Activity 处于不可见状态的时候,LiveData 发生了多次数据变化,当 Activity 恢复可见状态时,只有最新的那份数据才会通知给观察者,前面的数据在这种情况下相当于已经过期了,会被直接丢弃。
4.Room
ORM 也叫对象关系映射。简单来讲,我们使用的编程语言是面向对象语言,而使用的数据库则是关系型数据库,将面向对象的语言和面向关系的数据库之间建立一种映射关系,这就是 ORM 了。
使用 Room 进行增删改查
Room 主要由 Entity、Dao 和 Database 这 3 部分组成:
- Entity:用于定义封装实际数据的实体类,每个实体类都会在数据库中有一张对应的表,并且表中的列是根据实体类中的字段自动生成的。
- Dao:Dao 是数据访问对象的意思,通常会在这里对数据库的各项操作进行封装,在实际编程的时候,逻辑层就不需要和底层数据库打交道了,直接和 Dao 层进行交互即可。
- Database:用于定义数据库中的关键信息,包括数据库的版本号、包含哪些实体类以及提供 Dao 层的访问实例。
//build.gradle
apply plugin: 'kotlin-kapt'
defaultConfig {
...
javaCompileOptions {
annotationProcessorOptions {
arguments = ["room.schemaLocation":
"$projectDir/schemas".toString()]
}
}
}
implementation 'android.arch.persistence.room:runtime:1.1.1'
kapt 'android.arch.persistence.room:compiler:1.1.1'
//User.kt
package com.tomorrow.kotlindemo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
data class User(var firstName: String, var lastName: String, var age: Int) {
@PrimaryKey(autoGenerate = true)
var id: Long = 0
}
//UserDao.kt
package com.tomorrow.kotlindemo
import androidx.room.*
@Dao
interface UserDao {
@Insert
fun insertUser(user: User): Long
@Update
fun updateUser(newUser: User)
@Query("select * from User")
fun loadAllUsers(): List<User>
@Query("select * from User where age > :age")
fun loadUsersOlderThan(age: Int): List<User>
@Delete
fun deleteUser(user: User)
@Query("delete from User where lastName = :lastName")
fun deleteUserByLastName(lastName: String): Int
}
//AppDatabase.kt
package com.tomorrow.kotlindemo
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
@Database(version = 1, entities = [User::class])
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
companion object {
private var instance: AppDatabase? = null
@Synchronized
fun getDatabase(context: Context): AppDatabase {
instance?.let {
return it
}
return Room.databaseBuilder(context.applicationContext,
AppDatabase::class.java, "app_database")
.build().apply {
instance = this
}
}
}
}
MainActivity.kt
package com.tomorrow.kotlindemo
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import kotlin.concurrent.thread
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
thread {
val userDao = AppDatabase.getDatabase(this).userDao()
val user1 = User("Tom", "Brady", 40)
val user2 = User("Tom", "Hanks", 63)
user1.id = userDao.insertUser(user1)
user2.id = userDao.insertUser(user2)
Log.d("TAG", "zwm, user1.id: ${user1.id}, user2.id: ${user2.id}")
for(user in userDao.loadAllUsers()) {
Log.d("TAG", "zwm, $user")
}
user1.age = 55
userDao.updateUser(user1)
userDao.deleteUserByLastName("Hanks")
for(user in userDao.loadAllUsers()) {
Log.d("TAG", "zwm, $user")
}
}
}
}
日志打印:
2020-10-30 08:50:47.486 2402-2589/com.tomorrow.kotlindemo D/TAG: zwm, user1.id: 1, user2.id: 2
2020-10-30 08:50:47.501 2402-2589/com.tomorrow.kotlindemo D/TAG: zwm, User(firstName=Tom, lastName=Brady, age=40)
2020-10-30 08:50:47.501 2402-2589/com.tomorrow.kotlindemo D/TAG: zwm, User(firstName=Tom, lastName=Hanks, age=63)
2020-10-30 08:50:47.537 2402-2589/com.tomorrow.kotlindemo D/TAG: zwm, User(firstName=Tom, lastName=Brady, age=55)
由于 Room 会根据我们在项目中声明的注解来动态生成代码,因此这里一定要使用 kapt 引入 Room 的编译时注解库,而启用编译时注解功能则一定要先添加 kotlin-kapt 插件。注意,kapt 只能在 Kotlin 项目中使用,如果是 Java 项目的话,使用 annotationProcessor 即可。
如果是使用非实体类参数来增删改数据,那么也要编写 SQL 语句才行,而且这个时候不能使用 @Insert、@Delete 或 @Update 注解,而是都要使用 @Query 注解才行。
Room 是支持在编译时动态检查 SQL 语句语法的,也就是说,如果我们编写的 SQL 语句有语法错误,编译的时候就会直接报错,而不会将错误隐藏到运行的时候才发现,也算是大大减少了很多安全隐患吧。
由于数据库操作属于耗时操作,Room 默认是不允许在主线程中进行数据库操作的,不过为了方面测试,Room 还提供了一个更加简单的方法:(建议只在测试环境下使用)
@Synchronized
fun getDatabase(context: Context): AppDatabase {
instance?.let {
return it
}
return Room.databaseBuilder(context.applicationContext,
AppDatabase::class.java, "app_database")
.allowMainThreadQueries()
.build().apply {
instance = this
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val userDao = AppDatabase.getDatabase(this).userDao()
val user1 = User("Tom", "Brady", 40)
val user2 = User("Tom", "Hanks", 63)
user1.id = userDao.insertUser(user1)
user2.id = userDao.insertUser(user2)
Log.d("TAG", "zwm, user1.id: ${user1.id}, user2.id: ${user2.id}")
for(user in userDao.loadAllUsers()) {
Log.d("TAG", "zwm, $user")
}
user1.age = 55
userDao.updateUser(user1)
userDao.deleteUserByLastName("Hanks")
for(user in userDao.loadAllUsers()) {
Log.d("TAG", "zwm, $user")
}
}
Room 的数据库升级
如果你目前还只是在开发测试阶段,不想编写那么烦琐的数据库升级逻辑,Room 倒也提供了一个简单粗暴的方法,在构建 AppDatabase 实例的时候,加入一个 fallbackToDestructiveMigration() 方法,这样只要数据库进行了升级,Room 就会将当前的数据库销毁,然后再重新创建,随之而来的副作用就是之前数据库中的所有数据就全部丢失了:
@Synchronized
fun getDatabase(context: Context): AppDatabase {
instance?.let {
return it
}
return Room.databaseBuilder(context.applicationContext,
AppDatabase::class.java, "app_database")
.allowMainThreadQueries()
.fallbackToDestructiveMigration()
.build().apply {
instance = this
}
}
数据库升级1:
//Book.kt
package com.tomorrow.kotlindemo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
data class Book(var name: String, var pages: Int) {
@PrimaryKey(autoGenerate = true)
var id: Long = 0
}
//BookDao.kt
package com.tomorrow.kotlindemo
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
@Dao
interface BookDao {
@Insert
fun insertBook(book: Book): Long
@Query("select * from Book")
fun loadAllBooks(): List<Book>
}
//AppDatabase.kt
package com.tomorrow.kotlindemo
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
@Database(version = 2, entities = [User::class, Book::class])
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
abstract fun bookDao(): BookDao
companion object {
val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("create table Book (id integer primary key autoincrement not null, name text not null, pages integer not null)")
}
}
private var instance: AppDatabase? = null
@Synchronized
fun getDatabase(context: Context): AppDatabase {
instance?.let {
return it
}
return Room.databaseBuilder(context.applicationContext,
AppDatabase::class.java, "app_database")
.addMigrations(MIGRATION_1_2)
.build().apply {
instance = this
}
}
}
}
数据库升级2:
//Book.kt
package com.tomorrow.kotlindemo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
data class Book(var name: String, var pages: Int, var author: String) {
@PrimaryKey(autoGenerate = true)
var id: Long = 0
}
//AppDatabase.kt
package com.tomorrow.kotlindemo
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
@Database(version = 3, entities = [User::class, Book::class])
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
abstract fun bookDao(): BookDao
companion object {
val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("create table Book (id integer primary key autoincrement not null, name text not null, pages integer not null)")
}
}
val MIGRATION_2_3 = object : Migration(2, 3) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("alter table Book add column author text not null default 'unknown'")
}
}
private var instance: AppDatabase? = null
@Synchronized
fun getDatabase(context: Context): AppDatabase {
instance?.let {
return it
}
return Room.databaseBuilder(context.applicationContext,
AppDatabase::class.java, "app_database")
.addMigrations(MIGRATION_1_2)
.addMigrations(MIGRATION_2_3)
.build().apply {
instance = this
}
}
}
}
5.WorkManager
与后台相关的 API 变更大概有这些:从 4.4 系统开始 AlarmManager 的触发时间由原来的精准变为不精准,5.0 系统中加入了 JobScheduler 来处理后台任务,6.0 系统中引入了 Doze 和 App standby 模式用于降低手机被后台唤醒的频率,从 8.0 系统开始直接禁用了 Service 的后台功能,只允许使用前台 Service。
Google 推出了 WorkManager 组件,适合用于处理一些要求定时执行的任务,它可以根据操作系统的版本自动选择底层是使用 AlarmManager 实现还是 JobScheduler 实现,从而降低了我们的使用成本。另外,它还支持周期性任务、链式任务处理等功能,是一非常强大的工具。
WorkManager 和 Service 并不相同,也没有直接的联系。Service 是 Android 系统的四大组件之一,它在没有被销毁的情况下是一直保持在后台运行的。而 WorkManager 只是一个处理定时任务的工具,它可以保证即使在应用退出甚至手机重启的情况下,之前注册的任务仍然将会得到执行,因此 WorkManager 很适合用于执行一些定期和服务器进行交互的任务,比如周期性地同步数据,等等。
另外,使用 WorkManager 注册的周期性任务并不能保证一定会准时执行,这并不是 BUG,而是系统为了减少电量消耗,可能会将触发时间临近的接任务放在一起执行,这样可以大幅度地减少 CPU 被唤醒的次数,从而有效延长电池的使用时间。
WorkManager 的基本用法
//build.gradle
implementation 'androidx.work:work-runtime:2.2.0'
//SimpleWorker.kt
package com.tomorrow.kotlindemo
import android.content.Context
import android.util.Log
import androidx.work.Worker
import androidx.work.WorkerParameters
class SimpleWorker(context: Context, params: WorkerParameters) : Worker(context, params) {
override fun doWork(): Result {
Log.d("TAG", "zwm, do work in SimpleWorker")
return Result.success()
}
}
//MainActivity.kt
package com.tomorrow.kotlindemo
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.work.OneTimeWorkRequest
import androidx.work.WorkManager
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val request = OneTimeWorkRequest.Builder(SimpleWorker::class.java).build()
WorkManager.getInstance(this).enqueue(request)
}
}
日志打印:
2020-10-30 10:22:29.976 20279-26637/com.tomorrow.kotlindemo D/TAG: zwm, do work in SimpleWorker
使用 WorkManager 处理复杂的任务
让后台任务在指定的延迟时间后运行:
val request = OneTimeWorkRequest.Builder(SimpleWorker::class.java)
.setInitialDelay(2, TimeUnit.MINUTES)
.build()
给后台任务请求添加标签:
val request = OneTimeWorkRequest.Builder(SimpleWorker::class.java)
.addTag("simple")
.build()
取消后台任务:
WorkManager.getInstance(this).cancelAllWorkByTag("simple")
WorkManager.getInstance(this).cancelWorkById(request.id)
WorkManager.getInstance(this).cancelAllWork()
设置退避策略:
val request = OneTimeWorkRequest.Builder(SimpleWorker::class.java)
.setBackoffCriteria(BackoffPolicy.LINEAR, 10, TimeUnit.SECONDS)
.build()
LINEAR 代表下次重试时间以线性的方式延迟,EXPONENTIAL 代表下次重试时间以指数的方式延迟。
对后台任务的运行结果进行监听:
WorkManager.getInstance(this).getWorkInfoByIdLiveData(request.id).observe(this, Observer { workInfo ->
if(workInfo.state == WorkInfo.State.SUCCEEDED) {
Log.d("TAG", "zwm, do work succeeded")
} else if(workInfo.state == WorkInfo.State.FAILED) {
Log.d("TAG", "zwm, do work failed")
}
})
同样也可以调用 getWorkInfosByTagLiveData() 方法监听同一标签下所有后台任务请求的运行结果。
链式任务:
val sync = ...
val compress = ...
val upload = ...
WorkManager.getInstance(this)
.beginWith(sync)
.then(compress)
.then(upload)
.enqueue()
WorkManager 要求必须在前一个后台任务运行成功之后,下一个后台任务才会运行。也就是说,如果某个后台任务运行失败,或者被取消了,那么接下来的后台任务就都得不到运行了。
6.Kotlin:使用 DSL 构建专有的语法结构
利用高阶函数的特性,完成 DSL 定制:
//DSL.kt
package com.tomorrow.kotlindemo
class Dependency {
val libraries = ArrayList<String>()
fun implementation(lib: String) {
libraries.add(lib)
}
}
fun dependencies(block: Dependency.() -> Unit): List<String> {
val dependency = Dependency()
dependency.block()
return dependency.libraries
}
//MainActivity.kt
package com.tomorrow.kotlindemo
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val libraries = dependencies {
implementation ("com.squareup.retrofit2:retrofit:2.6.1")
implementation ("com.squareup.retrofit2:converter-gson:2.6.1")
}
for(lib in libraries) {
Log.d("TAG", "zwm, lib: $lib")
}
}
}
日志打印:
2020-10-30 11:08:32.979 28773-28773/? D/TAG: zwm, lib: com.squareup.retrofit2:retrofit:2.6.1
2020-10-30 11:08:32.979 28773-28773/? D/TAG: zwm, lib: com.squareup.retrofit2:converter-gson:2.6.1
由于 dependencies 函数接收一个函数类型参数,因此这里我们可以传入一个 Lambda 表达式。而此时的 Lambda 表达式中拥有 Dependency 类的上下文,因此当然就可以直接调用 Dependency 类中的 implementation() 方法来添加依赖库了。
十三、高级技巧
1.全局获取 Context 的技巧
//MyApplication.kt
package com.tomorrow.kotlindemo
import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
class MyApplication : Application() {
companion object {
@SuppressLint("StaticFieldLeak")
lateinit var context: Context
}
override fun onCreate() {
super.onCreate()
context = applicationContext
}
}
fun String.showToast(duration: Int = Toast.LENGTH_SHORT) {
Toast.makeText(MyApplication.context, this, duration).show()
}
fun Int.showToast(duration: Int = Toast.LENGTH_SHORT) {
Toast.makeText(MyApplication.context, this, duration).show()
}
"Hello Kotlin".showToast()
R.string.app_name.showToast()
2.使用 Intent 传递对象
使用 Intent 来传递对象通常有两种实现方式:Serializable 和 Parcelable。
Serializable 方式:
//Person.kt
package com.tomorrow.kotlindemo
import java.io.Serializable
class Person : Serializable {
var name = ""
var age = 0
}
//MainActivity.kt
package com.tomorrow.kotlindemo
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val person = Person()
person.name = "Tomorrow"
person.age = 10
val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("person_data", person)
startActivity(intent)
}
}
//SecondActivity.kt
package com.tomorrow.kotlindemo
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
class SecondActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)
val person = intent.getSerializableExtra("person_data") as Person
Log.d("TAG", "zwm, name: ${person.name} age: ${person.age}")
}
}
Parcelable 方式:
//Person.kt
package com.tomorrow.kotlindemo
import android.os.Parcel
import android.os.Parcelable
class Person(): Parcelable {
var name = ""
var age = 0
constructor(parcel: Parcel) : this() {
name = parcel.readString()
age = parcel.readInt()
}
override fun writeToParcel(dest: Parcel?, flags: Int) {
dest?.writeString(name)
dest?.writeInt(age)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<Person> {
override fun createFromParcel(parcel: Parcel): Person {
return Person(parcel)
}
override fun newArray(size: Int): Array<Person?> {
return arrayOfNulls(size)
}
}
}
//MainActivity.kt
package com.tomorrow.kotlindemo
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val person = Person()
person.name = "Tomorrow"
person.age = 10
val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("person_data", person)
startActivity(intent)
}
}
//SecondActivity.kt
package com.tomorrow.kotlindemo
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
class SecondActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)
val person = intent.getParcelableExtra("person_data") as Person
Log.d("TAG", "zwm, name: ${person.name} age: ${person.age}")
}
}
3.深色主题
允许系统使用 Force Dark 将应用强制转换成深色主题:
//res/values-v29/styles.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:forceDarkAllowed">true</item>
</style>
</resources>
Force Dark 就是这样一种简单粗暴的转换方式,并且它的转换效果通常是不尽如人意的。因此,不推荐使用这种自动化的方式来实现深色主题,而是应该使用更加传统的实现方式——手动实现:
//res/values/styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.DayNight.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
</resources>
//res/values/colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#008577</color>
<color name="colorPrimaryDark">#00574B</color>
<color name="colorAccent">#D81B60</color>
</resources>
//res/values-night/colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#303030</color>
<color name="colorPrimaryDark">#232323</color>
<color name="colorAccent">#008577</color>
</resources>
//res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/title_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="?android:attr/colorBackground">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textColor="?android:attr/textColorPrimary"
android:text="Hello Kotlin"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
可以使用以下方法判断当前系统是否是深色主题:
fun isDarkTheme(context: Context): Boolean {
val flag = context.resources.configuration.uiMode and
Configuration.UI_MODE_NIGHT_MASK
return flag == Configuration.UI_MODE_NIGHT_YES
}
由于 Kotlin 取消了按位运算符的写法,改成了使用英文关键字,and 关键字对应 Java 中的 & 运算符,or 关键字对应了 Java 中的 | 运算符,xor 关键字对应了 Java 中的 ^ 运算符。
4.将背景图和状态栏融合到一起的另一种方法
//res/values/styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
</resources>
//res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorAccent"
android:fitsSystemWindows="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
//MainActivity.kt
package com.tomorrow.kotlindemo
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val decorView = window.decorView
decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
window.statusBarColor = Color.TRANSPARENT
setContentView(R.layout.activity_main)
}
}
5.运行时权限封装
//InVisibleFragment.kt
package com.tomorrow.kotlindemo
import android.content.pm.PackageManager
import androidx.fragment.app.Fragment
typealias PermissionCallback = (Boolean, List<String>) -> Unit
class InVisibleFragment : Fragment() {
private var callback: PermissionCallback? = null
fun requestNow(cb: PermissionCallback, vararg permissions: String) {
callback = cb
requestPermissions(permissions, 1)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if(requestCode == 1) {
val deniedList = ArrayList<String>()
for((index, result) in grantResults.withIndex()) {
if(result != PackageManager.PERMISSION_GRANTED) {
deniedList.add(permissions[index])
}
}
val allGranted = deniedList.isEmpty()
callback?.let { it(allGranted, deniedList) }
}
}
}
//PermissionX.kt
package com.tomorrow.kotlindemo
import androidx.fragment.app.FragmentActivity
object PermissionX {
private const val TAG = "InVisibleFragment"
fun request(activity: FragmentActivity, vararg permissions: String, callback: PermissionCallback) {
val fragmentManager = activity.supportFragmentManager
val existedFragment = fragmentManager.findFragmentByTag(TAG)
val fragment = if(existedFragment != null) {
existedFragment as InVisibleFragment
} else {
val inVisibleFragment = InVisibleFragment()
fragmentManager.beginTransaction().add(inVisibleFragment, TAG).commitNow() //一定要调用commitNow,而不能调用commit
inVisibleFragment
}
fragment.requestNow(callback, *permissions) //*表示将一个数组转换成可变长度参数
}
}
//AndroidManifest.xml
<uses-permission android:name="android.permission.CALL_PHONE"/>
//MainActivity.kt
package com.tomorrow.kotlindemo
import android.Manifest
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
PermissionX.request(this, Manifest.permission.CALL_PHONE) { allGranted, deniedList ->
if(allGranted) {
call()
} else {
Toast.makeText(this, "You denied $deniedList", Toast.LENGTH_SHORT).show()
}
}
}
private fun call() {
try {
val intent = Intent(Intent.ACTION_CALL)
intent.data = Uri.parse("tel:10086")
startActivity(intent)
} catch (e: SecurityException) {
e.printStackTrace()
}
}
}
6.Kotlin:KTX
lifecycle-livedata-ktx
//build.gradle
implementation 'com.squareup.retrofit2:retrofit:2.6.1'
implementation 'com.squareup.retrofit2:converter-gson:2.6.1'
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.3.0-beta01"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.3"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.3"
//Gist.kt
package com.tomorrow.kotlindemo
data class Gist(val files: Map<String, GistFile>)
data class GistFile(val content: String)
//GistService.kt
package com.tomorrow.kotlindemo
import retrofit2.Call
import retrofit2.http.GET
interface GistService {
@GET("gists/c2a7c39532239ff261be")
fun getGist(): Call<Gist>
}
//ServiceCreator.kt
package com.tomorrow.kotlindemo
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object ServiceCreator {
private const val BASE_URL = "https://api.github.com/"
private val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
fun <T> create(serviceClass: Class<T>): T = retrofit.create(serviceClass)
inline fun <reified T> create(): T = create(T::class.java)
}
//GistNetwork.kt
package com.tomorrow.kotlindemo
import android.util.Log
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
object GistNetwork {
private val gistService = ServiceCreator.create<GistService>()
suspend fun getGist() = gistService.getGist().await()
private suspend fun <T> Call<T>.await(): T {
Log.d("TAG", "zwm, GistNetwork await, thread: ${Thread.currentThread().name}")
return suspendCoroutine { continuation ->
Log.d("TAG", "zwm, GistNetwork suspendCoroutine, thread: ${Thread.currentThread().name}")
enqueue(object : Callback<T> {
override fun onResponse(call: Call<T>, response: Response<T>) {
Log.d("TAG", "zwm, GistNetwork onResponse, thread: ${Thread.currentThread().name}")
val body = response.body()
if(body != null) continuation.resume(body)
else continuation.resumeWithException(RuntimeException("response body is null"))
}
override fun onFailure(call: Call<T>, t: Throwable) {
Log.d("TAG", "zwm, GistNetwork onFailure, thread: ${Thread.currentThread().name}")
continuation.resumeWithException(t)
}
})
}
}
}
//Repository.kt
package com.tomorrow.kotlindemo
import android.util.Log
import androidx.lifecycle.liveData
import kotlinx.coroutines.Dispatchers
object Repository {
fun getGist() = liveData(Dispatchers.IO) {
Log.d("TAG", "zwm, Repository getGist, thread: ${Thread.currentThread().name}")
val result = try {
val gist = GistNetwork.getGist()
Result.success(gist)
} catch (e: Exception) {
Result.failure<Gist>(e)
}
emit(result)
}
}
//MainViewModel.kt
package com.tomorrow.kotlindemo
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
class MainViewModel : ViewModel() {
private val searchLiveData = MutableLiveData<String>()
val gistLiveData = Transformations.switchMap(searchLiveData) {
Log.d("TAG", "zwm, MainViewModel switchMap, thread: ${Thread.currentThread().name}")
Repository.getGist()
}
fun getGist() {
Log.d("TAG", "zwm, MainViewModel getGist, thread: ${Thread.currentThread().name}")
searchLiveData.value = searchLiveData.value
}
}
//MainActivity.kt
package com.tomorrow.kotlindemo
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
class MainActivity : AppCompatActivity() {
private val viewModel by lazy { ViewModelProviders.of(this).get(MainViewModel::class.java) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewModel.gistLiveData.observe(this, Observer { result ->
Log.d("TAG", "zwm, observe result: ${result.getOrNull()}, thread: ${Thread.currentThread().name}")
})
viewModel.getGist()
}
}
日志打印:
2020-10-31 14:24:19.573 19020-19020/com.tomorrow.kotlindemo D/TAG: zwm, MainViewModel getGist, thread: main
2020-10-31 14:24:19.579 19020-19020/com.tomorrow.kotlindemo D/TAG: zwm, MainViewModel switchMap, thread: main
2020-10-31 14:24:19.609 19020-19086/com.tomorrow.kotlindemo D/TAG: zwm, Repository getGist, thread: DefaultDispatcher-worker-1
2020-10-31 14:24:19.660 19020-19086/com.tomorrow.kotlindemo D/TAG: zwm, GistNetwork await, thread: DefaultDispatcher-worker-1
2020-10-31 14:24:19.661 19020-19086/com.tomorrow.kotlindemo D/TAG: zwm, GistNetwork suspendCoroutine, thread: DefaultDispatcher-worker-1
2020-10-31 14:24:21.316 19020-19020/com.tomorrow.kotlindemo D/TAG: zwm, GistNetwork onResponse, thread: main
2020-10-31 14:24:21.322 19020-19020/com.tomorrow.kotlindemo D/TAG: zwm, observe result: Gist(files={OkHttp.txt=GistFile(content=
\\ //
\\ .ooo. //
.@@@@@@@@@.
:@@@@@@@@@@@@@:
:@@. '@@@@@' .@@:
@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@
:@@ :@@@@@@@@@@@@@@@@@. @@:
@@@ '@@@@@@@@@@@@@@@@@, @@@
@@@ '@@@@@@@@@@@@@@@@@, @@@
@@@ '@@@@@@@@@@@@@@@@@, @@@
@@@ '@@@@@@@@@@@@@@@@@, @@@
@@@ '@@@@@@@@@@@@@@@@@, @@@
@@@ '@@@@@@@@@@@@@@@@@, @@@
@@@@@@@@@@@@@@@@@
'@@@@@@@@@@@@@@@'
@@@@ @@@@
@@@@ @@@@
@@@@ @@@@
'@@' '@@'
:@@@.
.@@@@@@@: +@@ `@@ @@` @@ @@
.@@@@'@@@@: +@@ `@@ @@` @@ @@
@@@ @@@ +@@ `@@ @@` @@ @@
.@@ @@: +@@ @@@ `@@ @@` @@@@@@ @@@@@@ @@;@@@@@
@@@ @@@ +@@ @@@ `@@ @@` @@@@@@ @@@@@@ @@@@@@@@@
@@@ @@@ +@@ @@@ `@@@@@@@@@@` @@ @@ @@@ :@@
@@@ @@@ +@@@@@ `@@@@@@@@@@` @@ @@ @@# @@+
@@@ @@@ +@@@@@+ `@@ @@` @@ @@ @@: @@#
@@: .@@` +@@@+@@ `@@ @@` @@ @@ @@# @@+
@@@. .@@@ +@@ @@@ `@@ @@` @@ @@ @@@ ,@@
@@@@@@@@@ +@@ @@@ `@@ @@` @@@@ @@@@ @@@@#@@@@
@@@@@@@ +@@ #@@ `@@ @@` @@@@: @@@@: @@'@@@@@
@@:
@@:
@@:)}), thread: main
liveData() 函数是 lifecycle-livedata-ktx 库提供的一个非常强大且好用的功能,它可以自动构建并返回一个 LiveData 对象,然后在它的代码块中提供一个挂起函数的上下文,这样我们就可以在 liveData() 函数的代码块中调用任意的挂起函数了。
emit() 方法将包装的结果发射出去,类似于调用 LiveData 的 setValue() 方法来通知数据变化,只不过这里我们无法直接取得返回的 LiveData 对象,所以 lifecycle-livedata-ktx 库提供了这样一个替代方法。
liveData() 函数的线程参数类型指定成了 Dispatchers.IO,这样代码块中的所有代码就都运行在子线程中了。
lifecycle-viewmodel-ktx
//build.gradle
implementation 'com.squareup.retrofit2:retrofit:2.6.1'
implementation 'com.squareup.retrofit2:converter-gson:2.6.1'
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.3.0-beta01"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.3"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.3"
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0' //新增依赖
//MainViewModel.kt
package com.tomorrow.kotlindemo
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
class MainViewModel : ViewModel() {
val gistLiveData : LiveData<Result<Gist>>
get() = _gistLiveData
private val _gistLiveData = MutableLiveData<Result<Gist>>()
fun getGist() {
Log.d("TAG", "zwm, MainViewModel getGist, thread: ${Thread.currentThread().name}")
viewModelScope.launch {
Log.d("TAG", "zwm, MainViewModel viewModelScope, thread: ${Thread.currentThread().name}")
val result = try {
val gist = GistNetwork.getGist()
Result.success(gist)
} catch (e: Exception) {
Result.failure<Gist>(e)
}
_gistLiveData.value = result
}
}
}
日志打印:
2020-10-31 14:59:29.689 28621-28621/com.tomorrow.kotlindemo D/TAG: zwm, MainViewModel getGist, thread: main
2020-10-31 14:59:29.710 28621-28621/com.tomorrow.kotlindemo D/TAG: zwm, MainViewModel viewModelScope, thread: main
2020-10-31 14:59:29.756 28621-28621/com.tomorrow.kotlindemo D/TAG: zwm, GistNetwork await, thread: main
2020-10-31 14:59:29.757 28621-28621/com.tomorrow.kotlindemo D/TAG: zwm, GistNetwork suspendCoroutine, thread: main
2020-10-31 14:59:31.016 28621-28621/com.tomorrow.kotlindemo D/TAG: zwm, GistNetwork onResponse, thread: main
2020-10-31 14:59:31.017 28621-28621/com.tomorrow.kotlindemo D/TAG: zwm, observe result: Gist(files={OkHttp.txt=GistFile(content=
\\ //
\\ .ooo. //
.@@@@@@@@@.
:@@@@@@@@@@@@@:
:@@. '@@@@@' .@@:
@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@
:@@ :@@@@@@@@@@@@@@@@@. @@:
@@@ '@@@@@@@@@@@@@@@@@, @@@
@@@ '@@@@@@@@@@@@@@@@@, @@@
@@@ '@@@@@@@@@@@@@@@@@, @@@
@@@ '@@@@@@@@@@@@@@@@@, @@@
@@@ '@@@@@@@@@@@@@@@@@, @@@
@@@ '@@@@@@@@@@@@@@@@@, @@@
@@@@@@@@@@@@@@@@@
'@@@@@@@@@@@@@@@'
@@@@ @@@@
@@@@ @@@@
@@@@ @@@@
'@@' '@@'
:@@@.
.@@@@@@@: +@@ `@@ @@` @@ @@
.@@@@'@@@@: +@@ `@@ @@` @@ @@
@@@ @@@ +@@ `@@ @@` @@ @@
.@@ @@: +@@ @@@ `@@ @@` @@@@@@ @@@@@@ @@;@@@@@
@@@ @@@ +@@ @@@ `@@ @@` @@@@@@ @@@@@@ @@@@@@@@@
@@@ @@@ +@@ @@@ `@@@@@@@@@@` @@ @@ @@@ :@@
@@@ @@@ +@@@@@ `@@@@@@@@@@` @@ @@ @@# @@+
@@@ @@@ +@@@@@+ `@@ @@` @@ @@ @@: @@#
@@: .@@` +@@@+@@ `@@ @@` @@ @@ @@# @@+
@@@. .@@@ +@@ @@@ `@@ @@` @@ @@ @@@ ,@@
@@@@@@@@@ +@@ @@@ `@@ @@` @@@@ @@@@ @@@@#@@@@
@@@@@@@ +@@ #@@ `@@ @@` @@@@: @@@@: @@'@@@@@
@@:
@@:
@@:)}), thread: main
网友评论