google 响应式编程 agera 试用

2023-11-08 12:20

本文主要是介绍google 响应式编程 agera 试用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

google 在本月也发布了一个响应式框架:agera[超级不好发音] 关于响应式编程 可以参考我的博客RxJava与RxAndroid,这里不再赘述;

目前google这个agera框架还是测试版 不建议拉入正式项目 适合预研!


第一步:添加依赖  

   https://github.com/google/agera

  

  compile 'com.google.android.agera:agera:1.0.0-rc2'

  在她基础上google又扩展了几个框架:

   android.content 例如 广播和sharedPrefrence:             compile 'com.google.android.agera:content:1.0.0-rc2'

   database                                                                             compile 'com.google.android.agera:database:1.0.0-rc2'

   网络                                  compile 'com.google.android.agera:net:1.0.0-rc2'

 recyclerView的RxAdapter               compile 'com.google.android.agera:rvadapter:1.0.0-rc2'

 

第二步:当然是看官方例咯:


public class AgeraActivity extends Activityimplements Receiver<Bitmap>, Updatable {private static final ExecutorService NETWORK_EXECUTOR =newSingleThreadExecutor();private static final ExecutorService DECODE_EXECUTOR =newSingleThreadExecutor();private static final String BACKGROUND_BASE_URL ="http://www.gravatar.com/avatar/4df6f4fe5976df17deeea19443d4429d?s=";private Repository<Result<Bitmap>> background;private ImageView backgroundView;@Overrideprotected void onCreate(final Bundle savedInstanceState) {super.onCreate(savedInstanceState);// Set the content viewsetContentView(R.layout.activity_main);// Find the background viewbackgroundView = (ImageView) findViewById(R.id.background);// Create a repository containing the result of a bitmap request. Initially// absent, but configured to fetch the bitmap over the network based on// display size.background = repositoryWithInitialValue(Result.<Bitmap>absent()).observe() // Optionally refresh the bitmap on events. In this case never.onUpdatesPerLoop() // Refresh per Looper thread loop. In this case never.getFrom(new Supplier<HttpRequest>() {@NonNull@Overridepublic HttpRequest get() {DisplayMetrics displayMetrics = getResources().getDisplayMetrics();int size = Math.max(displayMetrics.heightPixels,displayMetrics.widthPixels);return httpGetRequest(BACKGROUND_BASE_URL + size).compile();}}) // Supply an HttpRequest based on the display size.goTo(NETWORK_EXECUTOR) // Change execution to the network executor.attemptTransform(httpFunction()).orSkip() // Make the actual http request, skip on failure.goTo(DECODE_EXECUTOR) // Change execution to the decode executor.thenTransform(new Function<HttpResponse, Result<Bitmap>>() {@NonNull@Overridepublic Result<Bitmap> apply(@NonNull HttpResponse response) {byte[] body = response.getBody();return absentIfNull(decodeByteArray(body, 0, body.length));}}) // Decode the response to the result of a bitmap, absent on failure.onDeactivation(SEND_INTERRUPT) // Interrupt thread on deactivation.compile(); // Create the repository}@Overrideprotected void onResume() {super.onResume();// Start listening to the repository, triggering the flowbackground.addUpdatable(this);}@Overrideprotected void onPause() {super.onPause();// Stop listening to the repository, deactivating itbackground.removeUpdatable(this);}@Overridepublic void update() {// Called as the repository is updated// If containing a valid bitmap, send to accept belowbackground.get().ifSucceededSendTo(this);}@Overridepublic void accept(@NonNull Bitmap background) {// Set the background bitmap to the background viewbackgroundView.setImageBitmap(background);}
}



接下来 将解析google官方的例子 也就是用法demo:

agera 是基于java观察者设计模式而搭建的框架 在agera中有两个基本组件 Observable和Updatable

/** Copyright 2015 Google Inc. All Rights Reserved.** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at**     http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/
package com.google.android.agera;import android.support.annotation.NonNull;/*** Notifies added {@link Updatable}s when something happens.** <p>Addition and removal of {@link Updatable}s has to be balanced. Multiple add of the same* {@link Updatable} is not allowed and shall result in an {@link IllegalStateException}. Removing* non-added {@link Updatable}s shall also result in an {@link IllegalStateException}.* Forgetting to remove an {@link Updatable} may result in memory/resource leaks.** <p>Without any {@link Updatable}s added an {@code Observable} may temporarily be* <i>inactive</i>. {@code Observable} implementations that provide values, perhaps through a* {@link Supplier}, do not guarantee an up to date value when <i>inactive</i>. In order to ensure* that the {@code Observable} is <i>active</i>, add an {@link Updatable}.** <p>Added {@link Updatable}s shall be called back on the same thread they were added from.*/
public interface Observable {/*** Adds {@code updatable} to the {@code Observable}.** @throws IllegalStateException if the {@link Updatable} was already added or if it was called* from a non-Looper thread*/void addUpdatable(@NonNull Updatable updatable);/*** Removes {@code updatable} from the {@code Observable}.** @throws IllegalStateException if the {@link Updatable} was not added*/void removeUpdatable(@NonNull Updatable updatable);
}


/** Copyright 2015 Google Inc. All Rights Reserved.** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at**     http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/
package com.google.android.agera;/*** Called when when an event has occurred. Can be added to {@link Observable}s to be notified* of {@link Observable} events.*/
public interface Updatable {/*** Called when an event has occurred.*/void update();
}


Updatable 就是观察者模式的观察者 而Observable就是观察者模式中的被观察者



Observable去通知Updatable更新 当Observable调用addUpdatable()时将会注册到Observable中 可以在Observable的addUpdatable方法中使用update()方法去更新:

package com.xuan.agera;import android.app.Activity;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.view.View;import com.google.android.agera.Observable;
import com.google.android.agera.Updatable;/*** @author xuanyouwu* @email xuanyouwu@163.com* @time 2016-04-27 14:14*/
public class MainActivity extends Activity {private Observable observable = new Observable() {@Overridepublic void addUpdatable(@NonNull Updatable updatable) {LogUtils.d("--------->addUpdatable:" + updatable);updatable.update();}@Overridepublic void removeUpdatable(@NonNull Updatable updatable) {LogUtils.d("--------->removeUpdatable:" + updatable);}};private Updatable updatable = new Updatable() {@Overridepublic void update() {LogUtils.d("------>更新了:" + SystemClock.elapsedRealtime());}};@Overrideprotected void onPause() {super.onPause();observable.removeUpdatable(updatable);}@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);findViewById(R.id.btn_0).setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {observable.addUpdatable(updatable);}});}
}


点击按钮后关闭页面的结果:

04-27 14:50:06.633 30298-30298/com.xuan.agera D/----->log:: --------->addUpdatable:com.xuan.agera.MainActivity$2@41835ef0
04-27 14:50:06.633 30298-30298/com.xuan.agera D/----->log:: ------>更新了:105528968
04-27 14:51:07.083 30298-30298/com.xuan.agera D/----->log:: --------->removeUpdatable:com.xuan.agera.MainActivity$2@41835ef0

可以看到 更新了updatable 在activity退出的时候移除了updatable


当然这你发现这只是简单的接口调用 其实你就错了 

请看:





他们有许多的实现类,不仅如此:还可以传递数据

public interface Repository<T> extends Observable, Supplier<T> {}

姑且理解为仓库  这个仓库又继承了提供者Supplier 

/*** A supplier of data. Semantically, this could be a factory, generator, builder, or something else* entirely. No guarantees are implied by this interface.*/
public interface Supplier<T> {/*** Returns an instance of the appropriate type. The returned object may or may not be a new* instance, depending on the implementation.*/@NonNullT get();
}

这就能传递数据了,哈哈哈  哈哈哈

package com.xuan.agera;import android.app.Activity;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.view.View;import com.google.android.agera.Observable;
import com.google.android.agera.Repositories;
import com.google.android.agera.Repository;
import com.google.android.agera.Supplier;
import com.google.android.agera.Updatable;/*** @author xuanyouwu* @email xuanyouwu@163.com* @time 2016-04-27 14:14*/
public class MainActivity extends Activity {final Supplier<Long> supplier = new Supplier<Long>() {@NonNull@Overridepublic Long get() {return SystemClock.elapsedRealtime();}};final Repository<Long> repository = Repositories.repositoryWithInitialValue(1L).observe().onUpdatesPerLoop().thenGetFrom(supplier).compile();@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);final Updatable updatable1 = new Updatable() {@Overridepublic void update() {LogUtils.d("------>更新了:" + repository.get());}};findViewById(R.id.btn_1).setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {try {repository.removeUpdatable(updatable1);} catch (IllegalStateException e) {}repository.addUpdatable(updatable1);}});}
}

点击button:

04-27 15:10:07.633 15599-15599/com.xuan.agera D/----->log:: ------>更新了:106729959
04-27 15:10:08.403 15599-15599/com.xuan.agera D/----->log:: ------>更新了:106730734
04-27 15:10:09.143 15599-15599/com.xuan.agera D/----->log:: ------>更新了:106731455
04-27 15:10:10.153 15599-15599/com.xuan.agera D/----->log:: ------>更新了:106732480
04-27 15:10:10.753 15599-15599/com.xuan.agera D/----->log:: ------>更新了:106733070
04-27 15:10:11.273 15599-15599/com.xuan.agera D/----->log:: ------>更新了:106733589


从仓库中添加数据然后自动调用update方法 然后又重仓库中获取到对应的数据  感觉有点l   一种不好说的感觉


先来学习一下这些组件吧:

Observable  agera中的被观察者,可以通知观察者进行更新

Updatable   agera中的观察者,观察Obserable

Supplier      agera中的数据仓库的车间 

Repository  仓库 就行流一样 将suppelier放在上面 又可以同个get方法来获取


简直一头雾水,没有RxJava好,google必须得承认,原谅这是rc版本,毕竟RxJava已经相当成熟与丰富


这篇关于google 响应式编程 agera 试用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/369811

相关文章

Java AOP面向切面编程的概念和实现方式

《JavaAOP面向切面编程的概念和实现方式》AOP是面向切面编程,通过动态代理将横切关注点(如日志、事务)与核心业务逻辑分离,提升代码复用性和可维护性,本文给大家介绍JavaAOP面向切面编程的概... 目录一、AOP 是什么?二、AOP 的核心概念与实现方式核心概念实现方式三、Spring AOP 的关

MySQL的JDBC编程详解

《MySQL的JDBC编程详解》:本文主要介绍MySQL的JDBC编程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录前言一、前置知识1. 引入依赖2. 认识 url二、JDBC 操作流程1. JDBC 的写操作2. JDBC 的读操作总结前言本文介绍了mysq

Python异步编程之await与asyncio基本用法详解

《Python异步编程之await与asyncio基本用法详解》在Python中,await和asyncio是异步编程的核心工具,用于高效处理I/O密集型任务(如网络请求、文件读写、数据库操作等),接... 目录一、核心概念二、使用场景三、基本用法1. 定义协程2. 运行协程3. 并发执行多个任务四、关键

AOP编程的基本概念与idea编辑器的配合体验过程

《AOP编程的基本概念与idea编辑器的配合体验过程》文章简要介绍了AOP基础概念,包括Before/Around通知、PointCut切入点、Advice通知体、JoinPoint连接点等,说明它们... 目录BeforeAroundAdvise — 通知PointCut — 切入点Acpect — 切面

C#异步编程ConfigureAwait的使用小结

《C#异步编程ConfigureAwait的使用小结》本文介绍了异步编程在GUI和服务器端应用的优势,详细的介绍了async和await的关键作用,通过实例解析了在UI线程正确使用await.Conf... 异步编程是并发的一种形式,它有两大好处:对于面向终端用户的GUI程序,提高了响应能力对于服务器端应

C# async await 异步编程实现机制详解

《C#asyncawait异步编程实现机制详解》async/await是C#5.0引入的语法糖,它基于**状态机(StateMachine)**模式实现,将异步方法转换为编译器生成的状态机类,本... 目录一、async/await 异步编程实现机制1.1 核心概念1.2 编译器转换过程1.3 关键组件解析

Django HTTPResponse响应体中返回openpyxl生成的文件过程

《DjangoHTTPResponse响应体中返回openpyxl生成的文件过程》Django返回文件流时需通过Content-Disposition头指定编码后的文件名,使用openpyxl的sa... 目录Django返回文件流时使用指定文件名Django HTTPResponse响应体中返回openp

Go语言数据库编程GORM 的基本使用详解

《Go语言数据库编程GORM的基本使用详解》GORM是Go语言流行的ORM框架,封装database/sql,支持自动迁移、关联、事务等,提供CRUD、条件查询、钩子函数、日志等功能,简化数据库操作... 目录一、安装与初始化1. 安装 GORM 及数据库驱动2. 建立数据库连接二、定义模型结构体三、自动迁

Python 异步编程 asyncio简介及基本用法

《Python异步编程asyncio简介及基本用法》asyncio是Python的一个库,用于编写并发代码,使用协程、任务和Futures来处理I/O密集型和高延迟操作,本文给大家介绍Python... 目录1、asyncio是什么IO密集型任务特征2、怎么用1、基本用法2、关键字 async1、async

Java并发编程之如何优雅关闭钩子Shutdown Hook

《Java并发编程之如何优雅关闭钩子ShutdownHook》这篇文章主要为大家详细介绍了Java如何实现优雅关闭钩子ShutdownHook,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起... 目录关闭钩子简介关闭钩子应用场景数据库连接实战演示使用关闭钩子的注意事项开源框架中的关闭钩子机制1.