使用Rxjava检测值更改 [英] Detecting value change using Rxjava

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

问题描述

我们可以检测是否使用RxJava更改了类成员值?在类中有一个变量var,现在我们可以在var的值使用RxJava更改时得到通知。

Can we detect if a class member value is getting changed using RxJava?? Say in a class there is a variable var, now can we get notified whenever the value of var changes using RxJava.

推荐答案

你可以使用这样的东西:

You can use something like this:

private final BehaviorSubject<Integer> subject = BehaviorSubject.create();
private Integer value=0;

public Observable<Integer> getUiElementAsObservable() {
    return subject;
}

public void updateUiElementValue(final Integer valueAdded) {
    synchronized (value) {
        if (value + valueAdded < 0)
            return;
        value += valueAdded;
        subject.onNext(value);
    }
}

并订阅如下:

compositeSubscription.add(yourClass.getUiElementAsObservable()
            .subscribe(new Action1<Integer>() {
                @Override
                public void call(Integer userMessage) {
                    setViews(userMessage,true);
                }
            }));

你必须为你想要订阅他们的变化的所有变量创建setter并调用onNext如果适用更改。

you have to create setter for all of your variables that you want something subscribe to their changes and call onNext if change applied.

****更新****

****UPDATE****


当观察者订阅 BehaviorSubject 时,它首先发出源Observable最近发出的项目

When an observer subscribes to a BehaviorSubject, it begins by emitting the item most recently emitted by the source Observable

您可以在此处查看其他类型的主题: http://reactivex.io/documentation/subject.html

you can see other type of subjects here: http://reactivex.io/documentation/subject.html

一些有用的链接:
关于被动编程: https://gist.github.com/staltz/868e7e9bc2a7b8c1f754
和rxjava: https://youtu.be/k3D0cWyNno4

这篇关于使用Rxjava检测值更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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