在Android中使用Observable [英] Using Observable in Android

查看:843
本文介绍了在Android中使用Observable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现一个导航视图,其中包含许多片段,这些片段完全取决于 MainActivity 中定义的值。我知道MainActivity中的变量可以使用MainActivity中定义的方法从其他片段访问来获取值,但是这里的问题是MainActivity中变量的值可能更改(在 AsyncThread 上运行)。现在,我要么更改代码,以便我的 Fragments根据片段本身中的某些事件更新其值,或者使用 SharedPreference 。但我不想使用SharedPreferences,也不必多次检查值的变化。

I want to implement a Navigation View with many fragments that depend totally on a value defined in the MainActivity. I know that variables in MainActivity can be accessed using method defined in MainActivity from other Fragments to get the value, but the catch here is that the value of the variable in MainActivity may change (which runs on an AsyncThread). Now, I either change the code such that my Fragments update their value based on some event in the fragment itself or use SharedPreference. But I don't want to use SharedPreferences, neither have to check for change in the value unnecessarily many times.

我知道在RxJS中,我们使用 Observable 以异步方式运行并以类似于传送带的方式工作。通过官方文档:Observable 进行的一些Google搜索确认了我对某些事情的怀疑类似于Android中可用,但找不到任何适当的教程或如何实现它的解释。所以,我正在寻找一个简单的代码片段,它可以清楚地说明Observable在Android中是如何工作的,如果它是Async,并且它的基础类似于它的RxJS实现。 (不,我不想要RxJS实现)

I know in RxJS, we use Observable that runs Asynchronously and works in a fashion similar to a conveyor belt. A bit of googling through the official docs : Observable confirmed my suspicion of something similar being available in Android, but couldn't find any proper Tutorial or explanation on how to implement it. So, am looking for a simple code snippet that might give clarity to how Observable works in Android and if it is Async and if its based similar to RxJS implementation of it. (No, I don't want RxJS implementation)

测试用例:

MainActivity : int a, b (need observable for both variables)
Frag1 : int a1 , b1, a1changed(),b1changed()
Frag2 : int a2 , b2, a2Changed(), b2changed()

MainActivity包含整数,其值在更改时应反映在Fragments的相应整数中并调用单独的函数对于正在注意到的变化的每个片段。

MainActivity contains integers whose value when changed should reflect in corresponding integers across the Fragments and calls separate function for each Fragment on the change being noticed.

推荐答案

这是一个带有活动的简单示例和一个片段但它与其他片段相同。

Here is a simple example with an Activity and a single Fragment but it will be the same with other fragments.

首先你需要创建一个代表你想要观察的值的类,在你的情况下它是一个简单的 int 所以创建一个包含这个 int 并扩展 Observable (它实现 Serializable 以简化活动和片段之间的交换):

First you need to create a class standing for the value you want to observe, in your case it's a simple int so create a class containing this int and that extends Observable (it implements Serializable to simplify exchange between activity and fragment):

...
import java.util.Observable;

public class ObservableInteger extends Observable implements Serializable {

    private int value;

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
        this.setChanged();
        this.notifyObservers(value);
    }
}

然后在活动中使用此observable int(活动布局)包含按钮 FrameLayout 用于显示片段 ):

Then use this observable int in an activity (activity layout contains a Button and a FrameLayout used to display a Fragment):

public class MainActivity extends Activity {

    private ObservableInteger a;
    private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Create observable int
        a = new ObservableInteger();
        // Set a default value to it
        a.setValue(0);

        // Create frag1
        Frag1 frag1 = new Frag1();
        Bundle args = new Bundle();
        // Put observable int (That why ObservableInteger implements Serializable)
        args.putSerializable(Frag1.PARAM, a);
        frag1.setArguments(args);

        // Add frag1 on screen
        getFragmentManager().beginTransaction().add(R.id.container, frag1).commit();

        // Add a button to change value of a dynamically
        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Set a new value in a
                a.setValue(a.getValue() + 1);
            }
        });
    }
}

最后,创建片段听取价值变化:

Finally, create a Fragment that listen a value change:

...
import java.util.Observer;

public class Frag1 extends Fragment {
    public static final String PARAM = "param";

    private ObservableInteger a1;
    private Observer a1Changed = new Observer() {
        @Override
        public void update(Observable o, Object newValue) {
            // a1 changed! (aka a changed)
            // newValue is the observable int value (it's the same as a1.getValue())
            Log.d(Frag1.class.getSimpleName(), "a1 has changed, new value:"+ (int) newValue);
        }
    };

    public Frag1() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            // Get ObservableInteger created in activity
            a1 = (ObservableInteger) getArguments().getSerializable(PARAM);
            // Add listener for value change
            a1.addObserver(a1Changed);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_blank, container, false);
    }
}

我尝试将我的变量命名为与你的相同,我希望它会对你有所帮助。

I try to name my variables the same as yours, I hope it will help you.

这篇关于在Android中使用Observable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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