[Android] Use LiveData more gracefully in Kotlin

Since the LiveData#Observerinterface is defined in Java and accepts a Nullableparameter, it is not compatible with Kotlin's SAM and NonNull syntax features:

  viewModel.order.observe(viewLifecycleOwner, Observe {
    
      
      it?.let {
    
     applyCurrentOrder(it) }
  })
  • Observe { .. }Cannot be omitted
  • ?.letVery redundant

Now using it lifecycle-livedata-ktxcan help us use LiveData better in Kotlin:

dependencies {
    
    
        def lifecycle_version = "2.1.0" // or higher
        ...
        implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
        ...
    }

Then we can optimize more in the code observe:

class MyViewModel: ViewModel() {
    
    
  private val _data: MutableLiveData<MyData> = MutableLiveData()
  val order: LiveData<MyData> get() = _data
  ..
  fun updateData(data: MyData) {
    
    
    _data.value = data
  }
}
import androidx.lifecycle.observe  //ktx的observe

class MyFragment: Fragment(R.layout.my_fragment) {
    
    
  private val viewModel: MyViewModel by viewModels()

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    
    
    viewModel.order.observe(viewLifecycleOwner) {
    
    
        // observe接受lambda,且it为NonNull
        applyData(it)
    }
  }

  fun applyData(order: Order) {
    
    
    ..
  }
}

It is expected that all AAC libraries will be rewritten in Kotlin in the future, and there will be no need for these Ktx libraries to bridge.

Guess you like

Origin blog.csdn.net/vitaviva/article/details/108897407
Recommended