LoginSignup
0
0

More than 3 years have passed since last update.

Recipe: LiveData.observe with NonNull

Last updated at Posted at 2020-06-02

Problem

  viewModel.order.observe(viewLifecycleOwner, Observe {  
      it?.let { applyCurrentOrder(it) }
  })

toooooo many redundant code for just observe NonNull object with LiveData.

Ingredients

  1. lifecycle-livedata-ktx version 2.1.0 or higher
  2. Kotlin

Metod

First.

Add a dependency lifecycle-livedata-ktx in app/build.gradle.

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

Second.(Optional)

If your project not apply Java8 yet.
add below in app/build.gradle.

android {
      ..
      compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
      }
      // For Kotlin projects
      kotlinOptions {
        jvmTarget = "1.8"
      }
    }

Third.

Implements your ViewModel(AAC) class as code below.

class MyOrderViewModel: ViewModel() {
  private val _order: MutableLiveData<Order> = MutableLiveData()
  val order: LiveData<Order> get() = _order
  ..
  // Important: don't update _order directly in other class. just call function.
  fun updateCurrentOrder(order: Order) {
    _order.value = order
  }
}

Fourth.

Observe data your Activity/Fragment class with ktx(important!!!).

// You must add LivedData.observe Kotlin extension function.
import androidx.lifecycle.observe

class MyOrderFragment: Fragment(R.layout.my_fragment) {
  private val viewModel: MyOrderViewModel by viewModels()

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    // No longer need to write just like viewModel.order.observe(viewLifecycleOwner, Obseve{})
    viewModel.order.observe(viewLifecycleOwner) {
        // No need null check
        applyCurrentOrder(it)
    }
  }

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

Additional Technique (Alternately)

If you already wrote a lot of MutableLiveData instead of LiveData, you can also do the following.


interface MyOrderViewModel {
  val order: LiveData<Order>
}

class MyOrderViewModelImpl: ViewModel(), MyOrderViewModel {
  override val order: MutableLiveData<Order> = MutableLiveData()
  ..
  fun updateCurrentOrder(order: Order) {
    this.order.value = order
  }
}
import androidx.lifecycle.observe

class MyOrderFragment: Fragment(R.layout.my_fragment) {
  private val viewModel: MyOrderViewModel by viewModels<MyOrderViewModelImpl>()
  ..
}

More Information

about lifecycle: https://developer.android.com/jetpack/androidx/releases/lifecycle
about java8: https://developer.android.com/studio/write/java8-support

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0