user23515317
user23515317

Reputation: 31

Listening for single live event in composables

I have a singleLiveEvent that emits from A class based on a result

  private val exampleSingleLiveEvent = SingleLiveEvent<Boolean>()

  open val show: SingleLiveEvent<Boolean>
    get() = exampleSingleLiveEvent

In my viewModel, I have it as following

  open val show: SingleLiveEvent<Boolean> get() = A.show

In my composable, I read it as

  val show by viewModel.show.observeAsState()

The issue is that the state of the single live event remains true after it is emitted. So every time I enter the compose, I see the value as true. I, however, want it to be true only when the
SingleLiveEvent is emitted, and not always.

What am I missing here?

I tried using SideEffect, LaunchedEffect and DisposableEffect but it did not help.

Upvotes: 1

Views: 64

Answers (1)

Eugene Troyanskii
Eugene Troyanskii

Reputation: 892

Unfortunately google doesn't find better solution then propose to create some function like consumeEvent:

fun consumeSomeSingleEvent() {
    exampleSingleLiveEvent = exampleSingleLiveEvent.value = false
}

You should call this function after your single event is emited and perform the logic. Here is an official documentation from google on how to work with events for now...

https://developer.android.com/topic/architecture/ui-layer/events#handle-viewmodel-events

Upvotes: 0

Related Questions