为什么我的 observable 从未在 kotlin android 协同程序中看到我的列表更新?

Why is my observable never seeing the update to my list within a kotlin android coroutine?

我正在尝试构建一个模仿本教程的上传应用程序:https://codelabs.developers.google.com/codelabs/kotlin-coroutines/#4

我在第 29 行设置了一个断点(我在其中注释 "I never reach this breakpoint. Why not?")。为什么我点击按钮没有到达这个断点?

MainActivity.kt

package com.example.uploadwithprogresssimple

import android.arch.lifecycle.*
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.constraint.ConstraintLayout
import android.support.design.widget.Snackbar
import android.widget.TextView
import kotlinx.coroutines.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val viewModel = ViewModelProviders.of(this)
            .get(MainViewModel::class.java)

        val scheduler: TextView = findViewById(R.id.scheduleUpload)
        val rootLayout: ConstraintLayout = findViewById(R.id.rootLayout)

        scheduler.setOnClickListener {
            viewModel.uploadVideo("/foobar/abc/def")
        }

        viewModel.status.observe( this, Observer {
            // I never reach this breakpoint. Why not?
            if (it != null) {
                var size = it.size
                Snackbar.make(rootLayout, "Size of video upload: ${size}", Snackbar.LENGTH_SHORT).show()
            }
        })
    }
}

data class VideoAsset(private val filename: String)

class MainViewModel : ViewModel() {

    private val viewModelJob = Job()

    private val uiScope = CoroutineScope(Dispatchers.Main + viewModelJob)

    private val _status = MutableLiveData<ArrayList<VideoAsset>>()

    val status: LiveData<ArrayList<VideoAsset>>
        get() = _status

    override fun onCleared() {
        super.onCleared()
        uiScope.cancel()
    }

    fun uploadVideo(filename: String) {
        uiScope.launch {
            delay(1_000)
            _status.value?.add( VideoAsset( filename) )
        }
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/rootLayout"
        tools:context=".MainActivity">

    <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Schedule upload"
            android:id="@+id/scheduleUpload"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>

</android.support.constraint.ConstraintLayout>

app/build.gradle 文件:

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'


android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.uploadwithprogresssimple"
        minSdkVersion 23
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

def kotlinCoroutines = "1.1.0"

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support:design:28.0.0'

    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

    implementation 'android.arch.lifecycle:extensions:1.1.1'

    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlinCoroutines"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$kotlinCoroutines"
}

在这种情况下,未到达断点,因为未调用 LiveData 对象的 setValue(T) 方法。调用 setValue(T) 会导致观察者调用他们的 onChanged() 方法。尝试更改您的代码以调用 setValue(T) 方法,即:

val list = _status.value ?: arrayListOf<VideoAsset>()
list.add(VideoAsset(filename))
_status.value = list

注意:Kotlin 中的 setValue(T) 被替换为 属性 赋值:_status.value = list 而不是 _status.setValue(list)