observe

inline fun <T> LifecycleOwner.observe(liveData: LiveData<T>, crossinline action: (T) -> Unit)

Observes a LiveData and executes an action when non-null values are emitted.

This extension provides a cleaner syntax for LiveData observation with automatic null filtering. The action is only invoked when the LiveData emits a non-null value.

Usage in Fragment/Activity

class MyFragment : Fragment() {
private val viewModel: MyViewModel by viewModels()

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)

observe(viewModel.userData) { user ->
binding.userName.text = user.name
binding.userEmail.text = user.email
}
}
}

Modern Alternative (Recommended)

Prefer StateFlow with collectWithLifecycle for new code:

collectWithLifecycle(viewModel.userStateFlow) { user ->
// Handle user update
}

Parameters

T

The type of data emitted by the LiveData

liveData

The LiveData to observe

action

Callback invoked with non-null values

See also