Help us understand the problem. What is going on with this article?

Kotlin の拡張関数で LiveData の observe をいい感じにする

More than 1 year has passed since last update.

Activity や Fragment で ViewModel の中の LiveData を監視したいとき、例えばこのようになるでしょう。

myViewModel.myLiveData.observe(this, Observer<String?> {
    if (it != null) {
        myTextView.text = it
    }
})

itString? 型です。では、Observer<String?>Observer<String> にするとどうでしょうか

myViewModel.myLiveData.observe(this, Observer<String> {
    if (it != null) {
        myTextView.text = it
    }
})

it は変わらず String? 型です。これは Observer インターフェイスが以下のようになっているためです。

// Java だよ
public interface Observer<T> {
    void onChanged(@Nullable T t);
}

Kotlin からどんな型 T が渡されるかにかかわらず、メソッドの引数は @Nullable です。

しかし、null には絶対にならない、あるいは、 null は無視していいという場合も多いでしょう。そこで、以下のような拡張関数を作っておきます。

fun <T> LiveData<T>.observeNonNull(owner: LifecycleOwner, observer: (T) -> Unit) {
    this.observe(owner, Observer {
        if (it != null) {
            observer(it)
        }
    })
}

そうすると、このように書くことができます。

myViewModel.myLiveData.observeNonNull(this, {
    myTextView.text = it
})

itString 型です。

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away