Android Weekly Notes #414

Android Weekly Issue #414

ViewModel and SavedStateHandle: always retain state

依赖:

implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version"

构造:

class MyViewModel(private val state: SavedStateHandle) : ViewModel() {
[...]
}

实例化:

override val model by viewModels()

如果有其他参数:

class MyViewModelFactory(owner: SavedStateRegistryOwner,
                                     private val myId: Int,
                                     defaultArgs: Bundle? = null
) : AbstractSavedStateViewModelFactory(owner, defaultArgs) {

    override fun  create(
        key: String,
        modelClass: Class,
        handle: SavedStateHandle
    ): T = MyViewModel(handle, myId) as T
}

实例化:

override val model by viewModels {
    MyViewModelFactory(this, args.myId)
}

拿值:

private val itemsLiveData = savedStateHandle.getLiveData("itemsKey")

杀死进程的命令:

adb shell am kill your.package.name

Kotlin withContext vs Async-await

假设有这么两个方法:

private suspend fun doLongRunningTaskOne(): String {
    delay(5000)
    return "One"
}

private suspend fun doLongRunningTaskTwo(): String {
    delay(5000)
    return "Two"
}

用async, 把两个返回值加起来:

fun startLongRunningTaskInParallel() {
    viewModelScope.launch {
        val resultOneDeferred = async { doLongRunningTaskOne() }
        val resultTwoDeferred = async { doLongRunningTaskTwo() }
        val combinedResult = resultOneDeferred.await() + resultTwoDeferred.await()
    }
}

如果用withContext:

fun startLongRunningTaskInParallel() {
    viewModelScope.launch {
        val resultOne = withContext(Dispatchers.IO) { doLongRunningTaskOne() }
        val resultTwo = withContext(Dispatchers.IO) { doLongRunningTaskTwo() }
        val combinedResult = resultOne + resultTwo
    }
}

这样是串行的.

Code

https://github.com/AU-COVIDSafe/mobile-android

https://github.com/wajahatkarim3/EasyFlipViewPager

https://github.com/igorwojda/android-ecosystem-cheat-sheet

https://github.com/igorwojda/android-showcase

学习Jetpact Compose:
https://github.com/vinaygaba/Learn-Jetpack-Compose-By-Example

Kotlin图片加载库:
https://github.com/coil-kt/coil

Videos

Room数据库迁移:
https://www.youtube.com/watch?v=tUGUNU6DPtk&list=PLU4MI50rsBvbk-4G-1cQf3oV2MtF5L17C&index=2&t=0s

你可能感兴趣的:(Android Weekly Notes #414)