当字符串值改变时 RxAndroid 更新 Field/Textview

RxAndroid Update Field/Textview when String Value Changes

我刚刚开始使用 RxJava/RxAndroid,我想知道我是否可以用它来解决以下问题。基本上,给定一个字段,比如一个文本视图和一个值,一个字符串,我正在寻找一种方法来在字符串的值发生变化时自动更新文本视图。我不确定我将如何将其实现为 Observable。让我演示一下;

String str = "Test"; //the string value
TextView textView = (TextView) findViewById(R.id.textView); //the textview

Observable o = //looking for this part. Want to observe the String str

o.subscribe(new Observer<String>() { //subscribe here looking for string changes

            @Override
            public void onCompleted() {
                System.out.println("Completed");
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(String s) {
                textView.setText(s); //update the textview here
            }

        });

//here is where the string changes, it could be hardcoded, user input, or   
//anything else really, I just want the textview to be updated automatically 
//without another setText

str = "Different String"; 

RxAndroid/RxJava 可以实现我正在寻找的东西吗?

最简单的方法是使用任何类型的 Subject,可能是 BehaviorSubjectPublishSubjectSubject 既是 Subscriber(因此您可以使用 onNext 将值放入其中)又是 Observable(因此您可以订阅它)。在这里查看差异的解释:http://reactivex.io/documentation/subject.html

所以,而不是

String str = "Test";

你会

BehaviorSubject<String> stringSubject = BehaviorSubject.<String>create("Test");

然后您可以直接订阅stringObservable

而不是像这样为变量分配新值:

str = "Hello World!";

你会做

stringSubject.onNext("Hello World!");

哦,永远不要让 onError 为空 - 这样做会悄悄地吞下之前可能发生的任何异常,您会坐下来想知道为什么什么都没有发生。至少写e.printStacktrace()