RxAndroid的使用方式3-Lambda

Lambda表达式和Rx非常契合, 可以省略大量的内部类, 如Func和Action.
我们把上个示例, 用Lambda再写一次, 功能相同.

如果编译器出现”Method references are not supported at this language level” 请按下alt+enter 然后选择 “Set language level to 8 - Lambdas, type annotations, etc.”

添加Gradle配置
在app下的build.gradle如下:

{% highlight null %}
apply plugin: ‘me.tatarka.retrolambda’

android {

}

{% endhighlight %}

在根目录下的build.gradle如下:
{% highlight null %}
buildscript {
repositories {
jcenter()
}
dependencies {
classpath ‘com.android.tools.build:gradle:2.1.0’
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
classpath ‘com.neenbedankt.gradle.plugins:android-apt:1.8’
classpath ‘me.tatarka:gradle-retrolambda:3.2.5’
}
}
{% endhighlight %}
源码如下:

{% highlight java %}
public class LambdaActivity extends Activity {

@Bind(R.id.simple_tv_text) TextView mTvText;

final String[] mManyWords = {"Hello", "I", "am", "your", "friend", "Spike"};
final List mManyWordList = Arrays.asList(mManyWords);

@Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_simple);
    ButterKnife.bind(this);

    // 添加字符串, 省略Action的其他方法, 只使用一个onNext.
    Observable obShow = Observable.just(sayMyName());

    // 先映射, 再设置TextView
    obShow.observeOn(AndroidSchedulers.mainThread())
            .map(String::toUpperCase).subscribe(mTvText::setText);

    // 单独显示数组中的每个元素
    Observable obMap = Observable.from(mManyWords);

    // 映射之后分发
    obMap.observeOn(AndroidSchedulers.mainThread())
            .map(String::toUpperCase)
            .subscribe(this::showToast);

    // 优化过的代码, 直接获取数组, 再分发, 再合并, 再显示toast, Toast顺次执行.
    Observable.just(mManyWordList)
            .observeOn(AndroidSchedulers.mainThread())
            .flatMap(Observable::from)
            .reduce(this::mergeString)
            .subscribe(this::showToast);
}

// 创建字符串
private String sayMyName() {
    return "Hello, I am your friend, Spike!";
}

// 显示Toast
private void showToast(String s) {
    Toast.makeText(LambdaActivity.this, s, Toast.LENGTH_SHORT).show();
}

// 合并字符串
private String mergeString(String s1, String s2) {
    return String.format("%s %s", s1, s2);
}

}

{% endhighlight %}

你可能感兴趣的:(rxjava)