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

相关文章

Linux 网络编程 --- 应用层

一、自定义协议和序列化反序列化 代码: 序列化反序列化实现网络版本计算器 二、HTTP协议 1、谈两个简单的预备知识 https://www.baidu.com/ --- 域名 --- 域名解析 --- IP地址 http的端口号为80端口,https的端口号为443 url为统一资源定位符。CSDNhttps://mp.csdn.net/mp_blog/creation/editor

【Python编程】Linux创建虚拟环境并配置与notebook相连接

1.创建 使用 venv 创建虚拟环境。例如,在当前目录下创建一个名为 myenv 的虚拟环境: python3 -m venv myenv 2.激活 激活虚拟环境使其成为当前终端会话的活动环境。运行: source myenv/bin/activate 3.与notebook连接 在虚拟环境中,使用 pip 安装 Jupyter 和 ipykernel: pip instal

【编程底层思考】垃圾收集机制,GC算法,垃圾收集器类型概述

Java的垃圾收集(Garbage Collection,GC)机制是Java语言的一大特色,它负责自动管理内存的回收,释放不再使用的对象所占用的内存。以下是对Java垃圾收集机制的详细介绍: 一、垃圾收集机制概述: 对象存活判断:垃圾收集器定期检查堆内存中的对象,判断哪些对象是“垃圾”,即不再被任何引用链直接或间接引用的对象。内存回收:将判断为垃圾的对象占用的内存进行回收,以便重新使用。

Go Playground 在线编程环境

For all examples in this and the next chapter, we will use Go Playground. Go Playground represents a web service that can run programs written in Go. It can be opened in a web browser using the follow

深入理解RxJava:响应式编程的现代方式

在当今的软件开发世界中,异步编程和事件驱动的架构变得越来越重要。RxJava,作为响应式编程(Reactive Programming)的一个流行库,为Java和Android开发者提供了一种强大的方式来处理异步任务和事件流。本文将深入探讨RxJava的核心概念、优势以及如何在实际项目中应用它。 文章目录 💯 什么是RxJava?💯 响应式编程的优势💯 RxJava的核心概念

函数式编程思想

我们经常会用到各种各样的编程思想,例如面向过程、面向对象。不过笔者在该博客简单介绍一下函数式编程思想. 如果对函数式编程思想进行概括,就是f(x) = na(x) , y=uf(x)…至于其他的编程思想,可能是y=a(x)+b(x)+c(x)…,也有可能是y=f(x)=f(x)/a + f(x)/b+f(x)/c… 面向过程的指令式编程 面向过程,简单理解就是y=a(x)+b(x)+c(x)

消除安卓SDK更新时的“https://dl-ssl.google.com refused”异常的方法

消除安卓SDK更新时的“https://dl-ssl.google.com refused”异常的方法   消除安卓SDK更新时的“https://dl-ssl.google.com refused”异常的方法 [转载]原地址:http://blog.csdn.net/x605940745/article/details/17911115 消除SDK更新时的“

Java并发编程之——BlockingQueue(队列)

一、什么是BlockingQueue BlockingQueue即阻塞队列,从阻塞这个词可以看出,在某些情况下对阻塞队列的访问可能会造成阻塞。被阻塞的情况主要有如下两种: 1. 当队列满了的时候进行入队列操作2. 当队列空了的时候进行出队列操作123 因此,当一个线程试图对一个已经满了的队列进行入队列操作时,它将会被阻塞,除非有另一个线程做了出队列操作;同样,当一个线程试图对一个空

生信代码入门:从零开始掌握生物信息学编程技能

少走弯路,高效分析;了解生信云,访问 【生信圆桌x生信专用云服务器】 : www.tebteb.cc 介绍 生物信息学是一个高度跨学科的领域,结合了生物学、计算机科学和统计学。随着高通量测序技术的发展,海量的生物数据需要通过编程来进行处理和分析。因此,掌握生信编程技能,成为每一个生物信息学研究者的必备能力。 生信代码入门,旨在帮助初学者从零开始学习生物信息学中的编程基础。通过学习常用

简单的角色响应鼠标而移动

actor类 //处理移动距离,核心是找到角色坐标在世界坐标的向量的投影(x,y,z),然后在世界坐标中合成,此CC是在地面行走,所以Y轴投影始终置为0; using UnityEngine; using System.Collections; public class actor : MonoBehaviour { public float speed=0.1f; CharacterCo