Android LiveData prevent receive the last value on observe

后端 未结 12 1296
自闭症患者
自闭症患者 2020-11-27 04:41

Is it possible to prevent LiveData receive the last value when start observing? I am considering to use LiveData as events.

For example eve

12条回答
  •  -上瘾入骨i
    2020-11-27 05:16

    There is no reason to use LiveData as something that it is not. If you need a separate behavior (something that doesn't retain the previous value), then you should use a component that doesn't retain the previous value -- instead of hacking around it ("remembering" that it had emitted and then forgetting to emit, etc.)

    You can add event-emitter library:

    implementation 'com.github.Zhuinden:live-event:1.1.0'
    

    from Jitpack: maven { url "https://jitpack.io" }

    Then you can do

    private val eventEmitter = EventEmitter()
    val controllerEvents: EventSource = eventEmitter
    

    and

    controllerEvents.observe(viewLifecycleOwner) { event: WordController.Events ->
        when (event) {
            is WordController.Events.NewWordAdded -> showToast("Added ${event.word}")
        }.safe()
    }
    

提交回复
热议问题