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 Activity
    implements 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;

  @Override
  protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Set the content view
    setContentView(R.layout.activity_main);

    // Find the background view
    backgroundView = (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
          @Override
          public 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
          @Override
          public 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
  }

  @Override
  protected void onResume() {
    super.onResume();
    // Start listening to the repository, triggering the flow
    background.addUpdatable(this);
  }

  @Override
  protected void onPause() {
    super.onPause();
    // Stop listening to the repository, deactivating it
    background.removeUpdatable(this);
  }

  @Override
  public void update() {
    // Called as the repository is updated
    // If containing a valid bitmap, send to accept below
    background.get().ifSucceededSendTo(this);
  }

  @Override
  public void accept(@NonNull Bitmap background) {
    // Set the background bitmap to the background view
    backgroundView.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就是观察者模式中的被观察者

google 响应式编程 agera 试用_第1张图片

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 [email protected]
 * @time 2016-04-27 14:14
 */
public class MainActivity extends Activity {

    private Observable observable = new Observable() {
        @Override
        public void addUpdatable(@NonNull Updatable updatable) {
            LogUtils.d("--------->addUpdatable:" + updatable);
            updatable.update();
        }

        @Override
        public void removeUpdatable(@NonNull Updatable updatable) {
            LogUtils.d("--------->removeUpdatable:" + updatable);
        }
    };
    private Updatable updatable = new Updatable() {
        @Override
        public void update() {
            LogUtils.d("------>更新了:" + SystemClock.elapsedRealtime());
        }
    };

    @Override
    protected void onPause() {
        super.onPause();
        observable.removeUpdatable(updatable);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.btn_0).setOnClickListener(new View.OnClickListener() {
            @Override
            public 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


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

请看:

google 响应式编程 agera 试用_第2张图片


google 响应式编程 agera 试用_第3张图片


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

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.
   */
  @NonNull
  T 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 [email protected]
 * @time 2016-04-27 14:14
 */
public class MainActivity extends Activity {

   
    final Supplier<Long> supplier = new Supplier<Long>() {
        @NonNull
        @Override
        public Long get() {
            return SystemClock.elapsedRealtime();
        }
    };
    final Repository<Long> repository = Repositories.repositoryWithInitialValue(1L).observe().onUpdatesPerLoop().thenGetFrom(supplier).compile();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final Updatable updatable1 = new Updatable() {
            @Override
            public void update() {
                LogUtils.d("------>更新了:" + repository.get());
            }
        };


        findViewById(R.id.btn_1).setOnClickListener(new View.OnClickListener() {
            @Override
            public 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 试用)