Skip to main content

AndroidでLiveDataのTransformationsを使ってみた

[書評]プロに追いつくAndroid 開発入門を読んで最新技術を理解した
を読んだマスタカ

ここで知ったTransformationsを試しに使ってみた


・コードの説明
postするのはNameViewModel.currentNameだけど
購読するのはNameViewModel.ikemenName
変換したのが流れてくる

 

・Main.kt

class MainActivity : AppCompatActivity() {
    private val model: NameViewModel by viewModels()

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

        val nameObserver = Observer<String> { newName ->
            name_text_view.text = newName
        }

//        model.currentName.observe(this, nameObserver)
        model.ikemenName.observe(this, nameObserver)

        button.setOnClickListener {
            val anotherName = "masterka"
            model.currentName.postValue(anotherName)
        }
    }
}

 

・NameViewModel.kt

class NameViewModel : ViewModel() {
    val currentName: MutableLiveData<String> by lazy {
        MutableLiveData<String>()
    }

    val ikemenName = Transformations.map(currentName) {
        "ikemen: $it"
    }
}

 

・gradle

    def lifecycle_version = "2.2.0"
    def activity_version = "1.1.0"

    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
    implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"
    implementation "androidx.activity:activity-ktx:$activity_version"

 

・layout

<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/name_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:text="button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@id/name_text_view"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        />

</androidx.constraintlayout.widget.ConstraintLayout>

 

・参考
https://developer.android.com/topic/libraries/architecture/livedata?hl=ja

関連記事:

Pocket