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

相关文章

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.

html5的响应式布局的方法示例详解

《html5的响应式布局的方法示例详解》:本文主要介绍了HTML5中使用媒体查询和Flexbox进行响应式布局的方法,简要介绍了CSSGrid布局的基础知识和如何实现自动换行的网格布局,详细内容请阅读本文,希望能对你有所帮助... 一 使用媒体查询响应式布局        使用的参数@media这是常用的

shell编程之函数与数组的使用详解

《shell编程之函数与数组的使用详解》:本文主要介绍shell编程之函数与数组的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录shell函数函数的用法俩个数求和系统资源监控并报警函数函数变量的作用范围函数的参数递归函数shell数组获取数组的长度读取某下的

springboot filter实现请求响应全链路拦截

《springbootfilter实现请求响应全链路拦截》这篇文章主要为大家详细介绍了SpringBoot如何结合Filter同时拦截请求和响应,从而实现​​日志采集自动化,感兴趣的小伙伴可以跟随小... 目录一、为什么你需要这个过滤器?​​​二、核心实现:一个Filter搞定双向数据流​​​​三、完整代码

揭秘Python Socket网络编程的7种硬核用法

《揭秘PythonSocket网络编程的7种硬核用法》Socket不仅能做聊天室,还能干一大堆硬核操作,这篇文章就带大家看看Python网络编程的7种超实用玩法,感兴趣的小伙伴可以跟随小编一起... 目录1.端口扫描器:探测开放端口2.简易 HTTP 服务器:10 秒搭个网页3.局域网游戏:多人联机对战4.

Java并发编程必备之Synchronized关键字深入解析

《Java并发编程必备之Synchronized关键字深入解析》本文我们深入探索了Java中的Synchronized关键字,包括其互斥性和可重入性的特性,文章详细介绍了Synchronized的三种... 目录一、前言二、Synchronized关键字2.1 Synchronized的特性1. 互斥2.

一文详解SpringBoot响应压缩功能的配置与优化

《一文详解SpringBoot响应压缩功能的配置与优化》SpringBoot的响应压缩功能基于智能协商机制,需同时满足很多条件,本文主要为大家详细介绍了SpringBoot响应压缩功能的配置与优化,需... 目录一、核心工作机制1.1 自动协商触发条件1.2 压缩处理流程二、配置方案详解2.1 基础YAML

如何解决Spring MVC中响应乱码问题

《如何解决SpringMVC中响应乱码问题》:本文主要介绍如何解决SpringMVC中响应乱码问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Spring MVC最新响应中乱码解决方式以前的解决办法这是比较通用的一种方法总结Spring MVC最新响应中乱码解