class SingleLiveEvent<T> : MutableLiveData<T>() {
private val pending = AtomicBoolean(false)
@MainThread
override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
if (hasActiveObservers()) {
Log.w(TAG, "Multiple observers registered but only one will be notified of changes.")
}
// Observe the internal MutableLiveData
super.observe(owner, Observer { t ->
if (pending.compareAndSet(true, false)) {
observer.onChanged(t)
}
})
}
@MainThread
override fun setValue(t: T?) {
pending.set(true)
super.setValue(t)
}
@MainThread
fun call() {
value = null
}
companion object {
private val TAG = "SingleLiveEvent"
}
}
ViewModel
class RegisterEventsViewModel : ViewModel() {
val startHomeActivityClickEvent = SingleLiveEvent<Any>()
fun onCancelClick() {
startHomeActivityClickEvent.call()
}
}
Activity
class RegisterEventsActivity: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.register_events)
registerModel = RegisterEventsViewModel()
binding.registerViewModel = registerModel
binding.lifecycleOwner = this
setupButtons()
}
private fun setupButtons() {
registerModel.startHomeActivityClickEvent.observe(
this, {
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
}
)
}
}
register_events.xml
<?xml version="1.0" encoding="utf-8"?>
<layout>
<data>
<variable
name="registerViewModel"
type="org.inu.events.viewmodel.RegisterEventsViewModel" />
</data>
...
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/button_cancel"
android:layout_width="0dp"
android:layout_height="52dp"
android:background="@drawable/drawable_btn_background"
android:text="@string/text_cancel"
android:textColor="@color/primary"
android:textFontWeight="400"
android:textSize="15sp"
android:onClick="@{ () -> registerViewModel.onCancelClick()}"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/button_next"
app:layout_constraintStart_toStartOf="parent" />
기록용으로 다음 코드는
https://algosketch.tistory.com/146
를 참조했습니다.