Android LiveData prevent receive the last value on observe

后端 未结 12 1323
自闭症患者
自闭症患者 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条回答
  •  忘掉有多难
    2020-11-27 05:29

    According to answer of jurij-pitulja.

    if we are using kotlin coroutines the solution look likes this.

    class Event(private val content: T) {
    
        var isHandled = false
        private set
    
        fun getContentIfNotHandled(): T? {
            return takeIf { !isHandled }?.let {
                isHandled = true
                content
            }
        }
    }
    

    Inside of view model class replacing Flow.asLiveData() into emit new Event

    val authResult: LiveData>> = _emailLiveData.switchMap { email ->
        liveData{
            repository.authRequest(email).collect{
                emit(Event(it))
            }
        }
    }
    

    Implementing observer method inside of fragment

    viewModel.authResult.observe(viewLifecycleOwner){
                it.getContentIfNotHandled()?.run {
                    onAuthRequestComplete(this)
                }
            }
    

提交回复
热议问题