zoukankan      html  css  js  c++  java
  • Android开发学习之路--RxAndroid之lambda

      RxJava的简单使用基本上也了解了,其实还有一个比较好玩的就是java8才有的lambda了。


    lambda在android studio下的环境搭建

    下载java8

      下面就来搭建下这个环境了,因为android不支持java8,所以需要用到一个开源库, retolambda,点这里。具体怎么使用基本上都有,这里简单地介绍下,首先就是下载java8了:下载java8,点这里

    修改配置工程文件

      下载好安装好后,需要修改build.gradle:

    // Top-level build file where you can add configuration options common to all sub-projects/modules.
    buildscript {
        repositories {
            jcenter()
        }
        dependencies {
            classpath 'com.android.tools.build:gradle:1.5.0'
            classpath 'me.tatarka:gradle-retrolambda:3.2.0'
    
            // NOTE: Do not place your application dependencies here; they belong
            // in the individual module build.gradle files
        }
    }
    
    allprojects {
        repositories {
            jcenter()
        }
    }
    
    task clean(type: Delete) {
        delete rootProject.buildDir
    }
    

      这里添加了me.tatarka:gradle-retrolambda:3.2.0。
      接着是 app目录下的build.gradle:

    apply plugin: 'com.android.application'
    apply plugin: 'me.tatarka.retrolambda'
    
    android {
        compileSdkVersion 23
        buildToolsVersion "23.0.2"
    
        defaultConfig {
            applicationId "com.jared.emrxandroidstudy"
            minSdkVersion 15
            targetSdkVersion 23
            versionCode 1
            versionName "1.0"
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
        compileOptions {
            sourceCompatibility JavaVersion.VERSION_1_8
            targetCompatibility JavaVersion.VERSION_1_8
        }
    }
    
    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        testCompile 'junit:junit:4.12'
        compile 'com.android.support:appcompat-v7:23.1.1'
    
        compile 'io.reactivex:rxandroid:1.1.0'
        compile 'io.reactivex:rxjava:1.1.0'
    }
    

    修改工程的jdk版本

      添加完后需要修改编译的jdk为java8:


    lambda在RxAndroid中简单使用

      修改完后,重新启动下工程,然后我们开始基于上一篇的文章继续了。这里对上一篇文章的代码通过lambda简化:

    private void createObservableByMap() {
            Log.d(TAG, "createObservableByMap");
            Observable.just(getHello()).map(new Func1<String, String>() {
                @Override
                public String call(String s) {
                    return s + " by eastmoon";
                }
            }).subscribe(onNextAction);
        }
    
    onNextAction = new Action1<String>() {
                @Override
                public void call(String s) {
                    mHello.setText(s);
                }
            };

      简化后如下所示:

    private void createObservableBylambda() {
            Log.d(TAG, "createObservableBylambda");
            Observable.just(getHello())
                    .map(s -> s + " by eastmoon")
                    .subscribe(s -> mHello.setText(s));
        }

      是不是非常清晰,非常的简洁优雅,这里先不分析。


    lambda表达式简介

    lambda简单介绍及例子

      简单理解下lambda吧,lambda是一种匿名表达式,关于lambda表达式这篇文章讲得不错:讲lambda比较好的文章。这里还是记录下当作学习吧,首先lambda的表达式一般是:

        (argument) -> (body)

      其中argument表示参数,body表示函数体要做的事。常用的表达式如下:

    (arg1, arg2...) -> { body }
    (type1 arg1, type2 arg2...) -> { body }

      具体一些是这样:

    (int a, int b) -> {  return a + b; } 
    () -> System.out.println("Hello World");
    (String s) -> { System.out.println(s); }
    () -> 42
    a  -> a + 5
    () -> { return 3.1415 };

    函数式接口简单介绍

      通过上述例子,基本上也理解了表达式怎么用了。那么什么情况下可以使用lambda表达式呢?这里有个函数式接口的概念,函数式接口就是指只包含一个抽象方法声明的接口。Runnable只有一个接口run,所以它可以用lambda表达式实现。普通的方式如下:

    Runnable r1 = new Runnable() {
                @Override
                public void run() {
                    Log.d(TAG, "testlambda");
                }
            };

      使用lambda表达式如下:

      Runnable r2 = () -> Log.d(TAG, "testlambda");

      从六行代码搞到了一行代码,是不是超级简洁优雅。来个例子试试水吧:

    private void testlambda() {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Log.d(TAG, "test by normal func");
                }
            }).start();
    
            new Thread(() -> Log.d(TAG, "test by lambda func")).start();
        }

      这里通过创建线程在run方法中输出信息,可以看出两种效果一模一样:

    03-11 09:18:39.453 27601-28067/? D/MainActivity: test by lambda func
    03-11 09:18:39.453 27601-28066/? D/MainActivity: test by normal func

    函数式接口地简单实现

      既然需要函数式接口,那么我们来简单的实现下函数式接口,新建FunctionLambda接口:

    package com.jared.emrxandroidstudy;
    
    /**
     * Created by jared on 16/3/11.
     */
    public interface FunctionLambda {
        public void hello();
    }

      接着编写类FunctionLambdaTest:

    package com.jared.emrxandroidstudy;
    
    /**
     * Created by jared on 16/3/11.
     */
    public class FunctionLambdaTest {
        public static void helloTest(FunctionLambda functionLambda) {
            functionLambda.hello();
        }
    }

      接着我们来实现下这个功能:

    private void testFunctionLambda() {
            FunctionLambdaTest.helloTest(new FunctionLambda() {
                @Override
                public void hello() {
                    Log.d(TAG, "test by normal testFunctionLambda");
                }
            });
    
            FunctionLambdaTest.helloTest(() -> Log.d(TAG, "test by lambda testFunctionLambda"));
        }
    

      输出信息如下:

    03-11 09:30:29.005 28776-28776/? D/MainActivity: test by normal testFunctionLambda
    03-11 09:30:29.005 28776-28776/? D/MainActivity: test by lambda testFunctionLambda

      效果一模一样,代码精简的不要不要的。


    lambda在RxAndroid中的使用分析

      好了,讲了这么多lambda表达式,还是看看rxAndroid用到的那个例子吧。这里再添下代码:

    private void createObservableBylambda() {
            Log.d(TAG, "createObservableBylambda");
            Observable.just(getHello())
                    .map(s -> s + " by eastmoon")
                    .subscribe(s -> mHello.setText(s));
        }

      首先是map方法,因为map方法中重写了call方法,传入的参数为s,函数体里面要做的事情是s+” by eastmoon”,所以就写成了s -> s+” by eastmoon”,由这可知就是s变为了s+” by eastmoon”。同理subscribe方法也一样,传入的需要处理的mHello.setText(s)。
      基本上lambda的简单使用ok了,接下去继续学习RxAndroid了。

  • 相关阅读:
    Select与Epoll的区别
    C++ 多态详解及常见面试题
    Linux进程状态详解及状态转换
    C++ 设计模式之单例模式
    DS 图解归并排序
    TCP三次握手,四次挥手详解及常见面试题
    Linux 进程间通信(管道、共享内存、消息队列、信号量)
    # maven
    # select sort 选择排序
    # gitlab与git私钥公钥
  • 原文地址:https://www.cnblogs.com/wuyida/p/6299945.html
Copyright © 2011-2022 走看看