【Android】在Kotlin中更优雅地使用LiveData

由于LiveData#Observer接口定义在Java中,且接受一个Nullable参数,导致其不能很好的兼容Kotlin的SAM以及NonNull等语法特性:

  viewModel.order.observe(viewLifecycleOwner, Observe {
    
      
      it?.let {
    
     applyCurrentOrder(it) }
  })
  • Observe { .. }不能省略
  • ?.let显得非常多余

现在使用lifecycle-livedata-ktx可以帮我们在Kotlin中更好的使用LiveData:

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

然后我们可以在代码中更加优化的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) {
    
    
    ..
  }
}

期待未来所有的AAC库都会用Kotlin重写,那时就不需要这些Ktx库做桥接了。

猜你喜欢

转载自blog.csdn.net/vitaviva/article/details/108897407