@ThreadSafe
class Example_11_ViewModel_Address implements IViewModel<Example_11_Model> {

  public final BehaviorSubject<Boolean> vm2v_edit = BehaviorSubject.create();

  public final BehaviorSubject<String> v2vm_address = BehaviorSubject.create();
  public final BehaviorSubject<String> vm2v_address = BehaviorSubject.create();

  public final BehaviorSubject<Boolean> vm2v_dirty =
      BehaviorSubject.create(false /* initial state */);

  public Example_11_ViewModel_Address() {
    wireInternally();
  }

  private void wireInternally() {
    v2vm_address
        .map(anschriftGemässView -> !anschriftGemässView.equals(vm2v_address.getValue()))
        .subscribe(vm2v_dirty);

    // Simulating some data
    vm2v_address.onNext("Koch Peti\nLadengasse 42\n4242 Vordemberg\nSchweiz");
  }

  @Override
  public void connectTo(final Example_11_Model model) {
    // NO-OP
  }
}
 CachedValuesHistogram getLatest() {
   startCachingStreamValuesIfUnstarted();
   if (rollingDistribution.hasValue()) {
     return rollingDistribution.getValue();
   } else {
     return null;
   }
 }
  private void wireInternally() {
    v2vm_address
        .map(anschriftGemässView -> !anschriftGemässView.equals(vm2v_address.getValue()))
        .subscribe(vm2v_dirty);

    // Simulating some data
    vm2v_address.onNext("Koch Peti\nLadengasse 42\n4242 Vordemberg\nSchweiz");
  }
示例#4
0
  public DownloadManager(
      Context context, SourceManager sourceManager, PreferencesHelper preferences) {
    this.context = context;
    this.sourceManager = sourceManager;
    this.preferences = preferences;

    gson = new Gson();
    queue = new DownloadQueue();

    downloadsQueueSubject = PublishSubject.create();
    threadsNumber = BehaviorSubject.create();
    runningSubject = BehaviorSubject.create();
  }
示例#5
0
  public Subscription subscribeData(Observer<List<GankBeauty>> observer) {
    if (mCache == null) {
      mCache = BehaviorSubject.create();
      Observable.create(
              new Observable.OnSubscribe<List<GankBeauty>>() {

                @Override
                public void call(Subscriber<? super List<GankBeauty>> subscriber) {
                  List<GankBeauty> itemList = getDataFromDisk(DATA_FILE_NAME);
                  if (ListUtils.isEmpty(itemList)) {
                    Logger.d("Load data from network");
                    setDataSource(DATA_SOURCE_NETWORK);
                    loadFromNetwork();
                  } else {
                    Logger.d("Load data from disk");
                    setDataSource(DATA_SOURCE_DISK);
                    subscriber.onNext(itemList);
                  }
                }
              })
          .subscribeOn(Schedulers.io())
          .subscribe(mCache);
    } else {
      Logger.d("Load data from memory.");
      setDataSource(DATA_SOURCE_MEMORY);
    }
    return mCache.observeOn(AndroidSchedulers.mainThread()).subscribe(observer);
  }
示例#6
0
  @Override
  public synchronized Observable<AccessToken> registerForAccessTokenUpdates(String code) {
    Timber.d("registerForAccessTokenUpdates");
    if (loadAccessTokenSubscription == null || loadAccessTokenSubscription.isUnsubscribed()) {
      Timber.d("no loading in progress, starting new one");
      loadAccessTokenSubscription =
          loadAccessTokenObservable(code)
              .subscribeOn(Schedulers.io())
              .observeOn(AndroidSchedulers.mainThread())
              .subscribe(
                  new DefaultSubscriber<AccessToken>() {

                    @Override
                    public void onError(Throwable throwable) {
                      Timber.e("accessTokenSubject.onError");
                      accessTokenSubject.onError(throwable);
                    }

                    @Override
                    public void onNext(AccessToken data) {
                      Timber.d("accessTokenSubject.onNext: " + data);
                      // Caching accessToken data
                      accessToken = data;
                      accessTokenSubject.onNext(accessToken);
                    }
                  });
    }
    return accessTokenSubject.asObservable();
  }
示例#7
0
public class RepositoryViewModel extends AbstractViewModel {
  private static final String TAG = RepositoryViewModel.class.getSimpleName();

  private final DataFunctions.GetUserSettings getUserSettings;
  private final DataFunctions.FetchAndGetGitHubRepository fetchAndGetGitHubRepository;

  private final BehaviorSubject<GitHubRepository> repository = BehaviorSubject.create();

  public RepositoryViewModel(
      @NonNull DataFunctions.GetUserSettings getUserSettings,
      @NonNull DataFunctions.FetchAndGetGitHubRepository fetchAndGetGitHubRepository) {
    Preconditions.checkNotNull(getUserSettings, "Gey User Settings cannot be null.");
    Preconditions.checkNotNull(
        fetchAndGetGitHubRepository, "Fetch And Get GitHub Repository cannot be null.");

    this.getUserSettings = getUserSettings;
    this.fetchAndGetGitHubRepository = fetchAndGetGitHubRepository;
    Log.v(TAG, "RepositoryViewModel");
  }

  @Override
  public void subscribeToDataStoreInternal(@NonNull CompositeSubscription compositeSubscription) {
    compositeSubscription.add(
        getUserSettings
            .call()
            .map(UserSettings::getSelectedRepositoryId)
            .switchMap(fetchAndGetGitHubRepository::call)
            .subscribe(repository));
  }

  @NonNull
  public Observable<GitHubRepository> getRepository() {
    return repository.asObservable();
  }
}
示例#8
0
  private void initializeSubscriptions() {
    if (downloadsSubscription != null && !downloadsSubscription.isUnsubscribed())
      downloadsSubscription.unsubscribe();

    if (threadsNumberSubscription != null && !threadsNumberSubscription.isUnsubscribed())
      threadsNumberSubscription.unsubscribe();

    threadsNumberSubscription =
        preferences.downloadThreads().asObservable().subscribe(threadsNumber::onNext);

    downloadsSubscription =
        downloadsQueueSubject
            .lift(new DynamicConcurrentMergeOperator<>(this::downloadChapter, threadsNumber))
            .onBackpressureBuffer()
            .observeOn(AndroidSchedulers.mainThread())
            .map(download -> areAllDownloadsFinished())
            .subscribe(
                finished -> {
                  if (finished) {
                    DownloadService.stop(context);
                  }
                },
                e -> Timber.e(e.getCause(), e.getMessage()));

    if (!isRunning) {
      isRunning = true;
      runningSubject.onNext(true);
    }
  }
示例#9
0
 public void UserLoginOut() {
   this.userAccountData = null;
   FileManager.getInstance().getChild(FileManager.Dir.Object, ACCOUNTFILE).delete();
   applyToken("");
   RongYunModel.getInstance().loginOut();
   userAccountDataBehaviorSubject.onNext(null);
 }
示例#10
0
/** Created by chanx on 16/5/20. */
public class DataStore {
  private static DataStore INSTANCE;

  // actual data store could be files, databases, or ContentProvider etc
  private final BehaviorSubject<List<GithubUser>> mUserListDataStoreStream =
      BehaviorSubject.create();

  private DataStore() {}

  public static DataStore getInstance() {
    if (INSTANCE == null) {
      synchronized (DataStore.class) {
        if (INSTANCE == null) {
          INSTANCE = new DataStore();
        }
      }
    }
    return INSTANCE;
  }

  public Observable<List<GithubUser>> getGithubUserListDataStore() {
    return mUserListDataStoreStream.asObservable();
  }

  public void fetchRandomGithubUsersToDataStore() {
    Intent intent = new Intent(GithubNetworkService.NETWORK_REQUEST_RANDOM_GITHUB_USERS);
    intent.setClass(DemoApplication.getContext(), GithubNetworkService.class);
    DemoApplication.getContext().startService(intent);
    Logger.d("send intent to NetworkService:" + intent);
  }

  public void setUserList(List<GithubUser> list) {
    mUserListDataStoreStream.onNext(list);
  }
}
  @Override
  public void onResume() {
    super.onResume();
    getListView().setDivider(null);
    App.i().loadCandidateBuzzes();

    lifecycle$.onNext(FragmentEvent.RESUME);
  }
示例#12
0
 /** {@inheritDoc} */
 @CallSuper
 @Override
 protected void onDestroy() {
   views.onCompleted();
   subscriptions.unsubscribe();
   for (Map.Entry<Integer, Subscription> entry : restartableSubscriptions.entrySet())
     entry.getValue().unsubscribe();
 }
示例#13
0
 public void setUserAccountData(UserAccountData userAccountData) {
   isUser = true;
   this.userAccountData = userAccountData;
   saveAccount();
   applyToken(userAccountData.getTokenApp());
   userAccountDataBehaviorSubject.onNext(userAccountData);
   Utils.Log("f**k");
 }
  @Override
  public void onDetach() {
    super.onDetach();

    // Reset the active callbacks interface to the dummy implementation.
    mCallbacks = sDummyCallbacks;

    lifecycle$.onNext(FragmentEvent.DETACH);
  }
 @Override
 public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
   super.onScrolled(recyclerView, dx, dy);
   int itemCount = mLayoutManager.getItemCount();
   int lastVisibleItemPosition = mLayoutManager.findLastVisibleItemPosition();
   if (lastVisibleItemPosition == itemCount - 1 && PhotosValidator.hasAfter(mPhotos)) {
     mFetchAfterSubject.onNext(mPhotos.getAfter());
   }
 }
  @Override
  public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    // Restore the previously serialized activated item position.
    if (savedInstanceState != null && savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
      setActivatedPosition(savedInstanceState.getInt(STATE_ACTIVATED_POSITION));
    }

    lifecycle$.onNext(FragmentEvent.CREATE_VIEW);
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Observable<List<CandidateBuzz>> candidateBuzzes$ = App.i().streams.candidateBuzzes$;
    CandidateBuzzAdapter adapter =
        new CandidateBuzzAdapter(getActivity(), R.layout.candidate_list_item);
    setListAdapter(adapter);
    syncListAdapter(candidateBuzzes$, adapter);

    lifecycle$.onNext(FragmentEvent.CREATE);
  }
  @Override
  public void onAttach(Activity activity) {
    super.onAttach(activity);

    // Activities containing this fragment must implement its callbacks.
    if (!(activity instanceof Callbacks)) {
      throw new IllegalStateException("Activity must implement fragment's callbacks.");
    }

    mCallbacks = (Callbacks) activity;

    lifecycle$.onNext(FragmentEvent.ATTACH);
  }
@ThreadSafe
class Example_10_ViewModel_Address implements IViewModel<Example_10_Model> {

  public final BehaviorSubject<Boolean> vm2v_edit = BehaviorSubject.create();

  public final BehaviorSubject<String> v2vm_address = BehaviorSubject.create();
  public final BehaviorSubject<String> vm2v_address = BehaviorSubject.create();

  public Example_10_ViewModel_Address() {
    wireInternally();
  }

  private void wireInternally() {
    // Simulating some data
    vm2v_address.onNext("Koch Peti\nLadengasse 42\n4242 Vordemberg\nSchweiz");
  }

  @Override
  public void connectTo(final Example_10_Model model) {
    // NO-OP
  }
}
示例#20
0
  public void destroySubscriptions() {
    if (isRunning) {
      isRunning = false;
      runningSubject.onNext(false);
    }

    if (downloadsSubscription != null && !downloadsSubscription.isUnsubscribed()) {
      downloadsSubscription.unsubscribe();
      downloadsSubscription = null;
    }

    if (threadsNumberSubscription != null && !threadsNumberSubscription.isUnsubscribed()) {
      threadsNumberSubscription.unsubscribe();
      threadsNumberSubscription = null;
    }
  }
public class BaseActivity extends FragmentActivity {
  @Nonnull
  private final BehaviorSubject<LifecycleEvent> lifecycleSubject = BehaviorSubject.create();

  protected final LifecycleMainObservable lifecycleMainObservable =
      new LifecycleMainObservable(
          new LifecycleMainObservable.LifecycleProviderActivity(lifecycleSubject, this));

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    lifecycleSubject.onNext(LifecycleEvent.CREATE);
  }

  @Override
  protected void onStart() {
    super.onStart();

    lifecycleSubject.onNext(LifecycleEvent.START);
  }

  @Override
  protected void onResume() {
    super.onResume();
    lifecycleSubject.onNext(LifecycleEvent.RESUME);
  }

  @Override
  protected void onPause() {
    lifecycleSubject.onNext(LifecycleEvent.PAUSE);
    super.onPause();
  }

  @Override
  protected void onStop() {
    lifecycleSubject.onNext(LifecycleEvent.STOP);
    super.onStop();
  }

  @Override
  protected void onDestroy() {
    lifecycleSubject.onNext(LifecycleEvent.DESTROY);
    super.onDestroy();
  }
}
示例#22
0
public class AppRouter extends Router {

  private final BehaviorSubject<RouteChange> screenChangeSubject = BehaviorSubject.create();

  public AppRouter(ScreenScooper screenScooper) {
    super(screenScooper);
  }

  public Observable<RouteChange> observeScreenChange() {
    return screenChangeSubject.asObservable();
  }

  @Override
  protected void onScoopChanged(RouteChange change) {
    screenChangeSubject.onNext(change);
  }
}
示例#23
0
public abstract class BaseActivity extends RoboActionBarActivity {

  private final BehaviorSubject<LifecycleEvent> lifecycleSubject = BehaviorSubject.create();

  public Observable<LifecycleEvent> lifecycle() {
    return lifecycleSubject.asObservable();
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    lifecycleSubject.onNext(LifecycleEvent.CREATE);
  }

  @Override
  protected void onStart() {
    super.onStart();
    lifecycleSubject.onNext(LifecycleEvent.START);
  }

  @Override
  protected void onResume() {
    super.onResume();
    lifecycleSubject.onNext(LifecycleEvent.RESUME);
  }

  @Override
  protected void onPause() {
    lifecycleSubject.onNext(LifecycleEvent.PAUSE);
    super.onPause();
  }

  @Override
  protected void onStop() {
    lifecycleSubject.onNext(LifecycleEvent.STOP);
    super.onStop();
  }

  @Override
  protected void onDestroy() {
    lifecycleSubject.onNext(LifecycleEvent.DESTROY);
    super.onDestroy();
  }
}
示例#24
0
/** Created by Administrator on 2016/3/18. */
public class RxBus {

  // PublishSubject仅会向Observer释放在订阅之后Observable释放的数据。
  private final Subject<Object, Object> publishBus =
      new SerializedSubject<>(PublishSubject.create());

  // AsyncSubject仅释放Observable释放的最后一个数据,并且仅在Observable完成之后。然而如果当Observable因为异常而终止,AsyncSubject将不会释放任何数据,但是会向Observer传递一个异常通知。
  private final Subject<Object, Object> asyncBus = new SerializedSubject<>(AsyncSubject.create());

  // 当Observer订阅了一个BehaviorSubject,它一开始就会释放Observable最近释放的一个数据对象,当还没有任何数据释放时,它则是一个默认值。接下来就会释放Observable释放的所有数据。
  // 如果Observable因异常终止,BehaviorSubject将不会向后续的Observer释放数据,但是会向Observer传递一个异常通知。
  private final Subject<Object, Object> behaviorBus =
      new SerializedSubject<>(BehaviorSubject.create());

  // 不管Observer何时订阅ReplaySubject,ReplaySubject会向所有Observer释放Observable释放过的数据。
  // 有不同类型的ReplaySubject,它们是用来限定Replay的范围,例如设定Buffer的具体大小,或者设定具体的时间范围。
  // 如果使用ReplaySubject作为Observer,注意不要在多个线程中调用onNext、onComplete和onError方法,因为这会导致顺序错乱,这个是违反了Observer规则的。
  private final Subject<Object, Object> replayBus = new SerializedSubject<>(ReplaySubject.create());
}
  private void initData() {
    // Initial load
    mPhotoService
        .getHotPhotos(null)
        .doOnNext(__ -> runOnUiThread(() -> mSwipeRefreshLayout.setRefreshing(true)))
        .compose(bindToLifecycle())
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(this::bind, this::onErrorDownloading);

    // Observable for loading more pages
    mFetchAfterSubject
        .filter(after -> !StringUtils.isNullOrEmpty(after))
        .distinctUntilChanged()
        .switchMap(mPhotoService::getHotPhotos)
        .doOnNext(__ -> runOnUiThread(() -> mSwipeRefreshLayout.setRefreshing(true)))
        .compose(bindUntilEvent(ActivityEvent.DESTROY))
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(this::merge, this::onErrorDownloading);
  }
 @Override
 protected void onDestroy() {
   lifecycleSubject.onNext(LifecycleEvent.DESTROY);
   super.onDestroy();
 }
 @Override
 protected void onStop() {
   lifecycleSubject.onNext(LifecycleEvent.STOP);
   super.onStop();
 }
 @Override
 protected void onPause() {
   lifecycleSubject.onNext(LifecycleEvent.PAUSE);
   super.onPause();
 }
 @Override
 protected void onResume() {
   super.onResume();
   lifecycleSubject.onNext(LifecycleEvent.RESUME);
 }
  @Override
  protected void onStart() {
    super.onStart();

    lifecycleSubject.onNext(LifecycleEvent.START);
  }