如何在Android中以多种方式观察livedata并进行多次观察? [英] How to observe the livedata with multiple observe for correct way in Android?

查看:460
本文介绍了如何在Android中以多种方式观察livedata并进行多次观察?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个活动",它将变为片段A,然后变为片段B,如下所示.

I have an Activity, and it will turn to the fragment-A and then turn to the fragment-B like the following.

Activity -> Fragment-A -> Fragment-B

Activity -> Fragment-A -> Fragment-B

情况1

这两个片段观察到相同的LiveData,以显示如下所示的SnackBar.

These two fragment observe the same LiveData for showing snackBar like the following .

viewModel.responseData.observe(this, Observer {
            it.getContentIfNotHandled()?.let {
            showSnackBar(it)
}

viewModel中的livedata:

The livedata in viewModel:

var responseData = MutableLiveData<Event<String>>()
responseData.value = Event("$message")

错误: 当我使用上面的代码时.它仅在片段A 中显示snackBar. 片段B 无法获取该值.

Error: When I use the above code. It only show the snackBar at fragment-A. The fragment-B can not get the value.

情况2

当我将代码更改为以下内容

When I change the code to the following

viewModel.responseData.observe(this, Observer {
            showSnackBar(it.peekContent())
})

两个片段都可以获取值.

The both fragment can get the value.

错误:

关闭片段后,再次旋转.因为responseData的值仍然存在,所以显示了snackBar. 但是我没有发送消息.

After close the fragment and turn again. It show the snackBar because the value of responseData still exist. But I did not send the message.

Event类参考如下:

/*
 * Copyright (C) 2019 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package bbin.mobile.ballbet.support

import androidx.lifecycle.Observer
import timber.log.Timber

/**
 * Used as a wrapper for data that is exposed via a LiveData that represents an event.
 */
open class Event<out T>(private val content: T) {

    var hasBeenHandled = false
        private set // Allow external read but not write

    /**
     * Returns the content and prevents its use again.
     */
    fun getContentIfNotHandled(): T? {
        return if (hasBeenHandled) {
            null
        } else {
            hasBeenHandled = true
            content
        }
    }

    /**
     * Returns the content, even if it's already been handled.
     */
    fun peekContent(): T = content
}

/**
 * An [Observer] for [Event]s, simplifying the pattern of checking if the [Event]'s content has
 * already been handled.
 *
 * [onEventUnhandledContent] is *only* called if the [Event]'s contents has not been handled.
 */
class EventObserver<T>(private val onEventUnhandledContent: (T) -> Unit) : Observer<Event<T>> {
    override fun onChanged(event: Event<T>?) {
        event?.getContentIfNotHandled()?.let {
            onEventUnhandledContent(it)
        }
    }
}

我希望片段为他们显示正确的SnackBar消息.

I want the fragment show the correct snackBar message for them.

如何在Android中以正确的方式观察livedata的多个片段?

How to observe the livedata for multiple fragment for correct way in Android?

谢谢.

推荐答案

您正在正确地观察LiveData,这是Event类的设计方式.

You are observing the LiveData correctly, it is how the Event class is designed.

完成时

viewModel.responseData.observe(this, Observer {
            it.getContentIfNotHandled()?.let {
            showSnackBar(it)
}

getContentIfNotHandled将仅返回一次内容,直到再次设置新值为止.如果FragmentA使用此第一个FragmentB,将无法使用相同的值.这是peekContent起作用的原因,因为即使事件已被消耗,它也会始终返回当前值.

getContentIfNotHandled will return content only once until there is a new value set again. If FragmentA consumes this first FragmentB will not be able to consume the same value. This is the reason peekContent works since it will always return the current value even though the event has been consumed.

如果有确凿的理由需要在两个片段中都显示此Snackbar消息,建议您在每个片段的LiveData实例上进行观察.

If there is a solid reason where you need to show this Snackbar msg in both fragments I suggest you observe on different LiveData instances for each fragment.

您可以通过在每次调用viewModel.getResponseData()时返回一个新的LiveData<Event<String>>来实现.

You could do this by returning a new LiveData<Event<String>> everytime viewModel.getResponseData() is invoked.

这篇关于如何在Android中以多种方式观察livedata并进行多次观察?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆