简体   繁体   English

在onChanged()回调,Livedata中解析不同的对象

[英]Parse different objects in onChanged() callback, Livedata

I want to listen to value changes in different fields in an activity. 我想听听活动中不同领域的价值变化。 So I have implemented the Observer interface, and bind these fields. 因此,我已经实现了Observer接口,并绑定了这些字段。 How do I differentiate which value is changed in onChanged() since there is one callback for both variables or what is the best practice/efficient way (in terms of memory consumption) to parse incoming objects in onChanged() ? 我如何区分onChanged()更改的值,因为两个变量都有一个回调,或者解析onChanged()传入对象的最佳实践/有效方式(就内存消耗而言)是什么?

public abstract class BaseActivity extends AppCompatActivity implements Observer {

    public MutableLiveData<Integer> status;
    public MutableLiveData<UserAccount> userAccount;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        status.observe(this, this);
        userAccount.observe(this, this);
    }

    @Override
    public void onChanged(@NonNull Object o) {
        // Best practice to parse/know different object types?
    }
}

You should avoid implementing in this manner since the types (Integer,UserAccount) for the Observer is different. 由于观察者的类型(Integer,UserAccount)不同,因此应避免以这种方式实现。

Since there is not status object indicating which MutableLiveData obj received the value, one work around is to use instanceOf operator in onChanged and check if its Integer or UserAccount . 由于没有状态对象指示哪个MutableLiveData obj接收到该值,因此一种解决方法是在onChanged使用instanceOf运算符,并检查其IntegerUserAccount

I would recommend you to avoid this since it would not be a great design and difficult to maintain. 我建议您避免这种情况,因为它不是一个很好的设计并且很难维护。

You can make it separation of concern by creating two Observers one with Observer<Integer> and another with Observer<UserAccount> as follows: 您可以通过创建两个Observers Observer<Integer>和另一个Observer<UserAccount>来使关注点分离,如下所示:

class StatusObserver implements Observer<Integer> {
    @Override
    public void onChanged(@NonNull Integer status) {
        // do something
    }
}

class UserAccountObserver implements Observer<UserAccount> {
    @Override
    public void onChanged(@NonNull UserAccount userAccount) {
        // do something
    }
}

This is much cleaner approach, easy to maintain and since you have separated it, changes to handling of status won't impact handling of userAccount. 这是一种更简洁的方法,易于维护,并且由于您已将其分开,因此更改状态处理不会影响userAccount的处理。

Alternatively, you can implement them as anonymous classes as follows: 或者,您可以将它们实现为匿名类,如下所示:

status.observe(this, new Observer<Integer>() {
    @Override
    public void onChanged(@Nullable final Integer integer) {

    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM