为什么可观察到的我从来没有在kotlin android协程中看到我列表的更新?

时间:2018-12-31 19:41:33

标签: android kotlin kotlin-coroutines

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

我在第29行上设置了一个断点(我已在其中评论“我从未到达此断点。为什么不呢?”)。当我单击按钮时,为什么不能到达此断点?

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"
}

1 个答案:

答案 0 :(得分:1)

在这种情况下,由于未调用setValue(T)对象的LiveData方法而未达到断点。调用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)