Generates DSL for LiveData observation.
loginViewModel.apply {
mySampleLiveData(this@MainActivity) { userName ->
println(userName)
...
}
liveDataWithoutLifeCycleOwner { userName ->
println(userName)
...
}
}
- You need to add
@LiveDataDSL
annotation on your LiveData:
@LiveDataDSL
protected val sampleLiveData = MutableLiveData<String>()
@LiveDataDSL
protected val myOtherLiveData = MutableLiveData<Int>()
Also make sure that your LiveData has protected
or public
modifier.
- Make sure that your view model class is extendable:
open class SampleViewModel : ViewModel() {
...
}
OR
abstract class SampleViewModel : ViewModel() {
...
}
-
Build your project, and use the generated ViewModel class in your view(Fragment, Activity or whatever).
The generated ViewModel will be named${ORIGINAL_CLASS_NAME}_DSL.kt
, for example, if your ViewModel is namedSampleViewModel.kt
, then the generated ViewModel will be namedSampleViewModel_DSL.kt
-
Use the generated ViewModel:
val sampleViewModel = ViewModelProviders.of(this)[SampleViewModel_DSL::class.java]
sampleViewModel.apply{
sampleLiveData(this@MainActivity) {
// This is where observation happens, you can use `it` receiver as observed value
...
}
myOtherLiveData(this@MainActivity) { myValue ->
// This is where observation happens, you can use `myValue` receiver as observed value
...
}
}
You can also observe your live data without passing LifecycleOwner, but it will use observeForever
.
private lateinit var function: FunctionResult<Observer<String>, LiveData<String>>
override fun onCreate(bundle: Bundle?) {
val sampleViewModel = ViewModelProviders.of(this)[SampleViewModel_DSL::class.java]
sampleViewModel.apply{
function = sampleLiveData {
// This is where observation happens, you can use `it` receiver as observed value
...
}
myOtherLiveData { myValue ->
// This is where observation happens, you can use `myValue` receiver as observed value
...
}
}
}
override fun onDestroy() {
super.onDestroy()
function.apply { liveData.removeObservers(observer) }
}
You can set custom name for the DSL function through @LiveData(name = "customName")
.
open class SampleViewModel : ViewModel() {
@LiveData("helloWorld")
protected val customLiveData = MutableLiveData<Any>()
}
val sampleViewModel = ViewModelProviders.of(this)[SampleViewModel_DSL::class.java].apply {
helloWorld {
...
}
}
dependencies {
implementation "com.phelat:livedatadsl:1.0.0-alpha7"
kapt "com.phelat:livedatadsl-processor:1.0.0-alpha7"
}
dependencies {
implementation "com.phelat:livedatadsl:1.0.0-alpha7"
kapt "com.phelat:livedatadsl-processor-x:1.0.0-alpha7"
}