Tip using LiveData

Tram Ho

Since its launch more than two years ago, LiveData has become an integral part of reactive programing. However, it is still not really perfect when we use The problem lies in observe function

However, with livedata-ktx version 2.2.0, we have an extension function

So we don’t need to use it twice or we need unnecessary null checking. We can actually write code because it always handles nullability correctly.

But sometimes we don’t get livedata from library. Sometimes we have to create them ourselves. While an observer function allows us to lose some templates at the receiving place, it does not solve all the problems.

In the above code we can see the problem. The data type is assumed to be String, but the value still returns the null value. You can easily understand why by looking at Java code

But the more dangerous problem is that even though we defined in MutableLiveData <String> as non-nullable, we can still set its value to null.

Same as before, this is due to Java. It has no way to enforce nullable matches

But we can fix them

Because LiveData is just a class, we can inherit them and add public set value methods so that it can be changed.

  • If you are using MutiableLiveData you can easily modify them with replace =)))

    Previously you could assign a value using null values

    And now we can not assign values ​​with null as before anymore

    If you find it interesting you can try using them



Chia sẻ bài viết ngay

Nguồn bài viết : Viblo