Nullability and LiveData with Kotlin

前端 未结 8 1592
梦谈多话
梦谈多话 2021-02-19 02:57

I want to use LiveData with Kotlin and have values that should not be null. How do you deal with this? Perhaps a wrapper around LiveData? Searching for good patterns here .. As

相关标签:
8条回答
  • 2021-02-19 03:23

    You can do this

    normalLiveData
      .nonNull()
      .observe(this, { result -> 
        // result is non null now
      })
    

    There is an article about it. https://medium.com/@henrytao/nonnull-livedata-with-kotlin-extension-26963ffd0333

    0 讨论(0)
  • 2021-02-19 03:27

    You can create an extension for LifecycleOwner

    fun <T> LifecycleOwner.observe(liveData: LiveData<T?>, lambda: (T) -> Unit) {
        liveData.observe(this, Observer { if (it != null) lambda(it) })
    }
    

    and then in your fragment/activity

    observe(liveData) { ... }
    
    0 讨论(0)
提交回复
热议问题