rx.subscriptions.Subscriptions Java Examples

The following examples show how to use rx.subscriptions.Subscriptions. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Chest.java    From Iron with Apache License 2.0 6 votes vote down vote up
public <T> Observable<T> get(final String key) {
    return Observable.create(new Observable.OnSubscribe<T>() {
        @Override
        public void call(final Subscriber<? super T> subscriber) {
            final DataChangeCallback<T> callback = new DataChangeCallback<T>(key) {
                @Override
                public void onDataChange(T value) {
                    if (!subscriber.isUnsubscribed()) {
                        subscriber.onNext(value);
                    }
                }
            };
            Chest.this.addOnDataChangeListener(callback);
            subscriber.add(Subscriptions.create(new Action0() {
                @Override
                public void call() {
                    Chest.this.removeListener(callback);
                }
            }));
            subscriber.onNext(Chest.this.<T>read(key));
        }
    }).compose(this.<T>applySchedulers());
}
 
Example #2
Source File: GetFeedImpl.java    From protohipster with Apache License 2.0 6 votes vote down vote up
private Observable<Map<String, Integer>> getCountLikersObservable(final List<String> userIds) {
    return Observable.create(new Observable.OnSubscribeFunc<Map<String, Integer>>() {
        @Override
        public Subscription onSubscribe(final Observer<? super Map<String, Integer>> observer) {
            likeDataSource.getCountLikesForUser(userIds, new GetCountLikesCallback() {
                @Override
                public void countUsers(Map<String, Integer> countLikers) {
                    observer.onNext(countLikers);
                    observer.onCompleted();
                }
            });

            return Subscriptions.empty();
        }
    });
}
 
Example #3
Source File: ArticleDetailViewModel.java    From Qiitanium with MIT License 6 votes vote down vote up
public void loadArticle(String id) {
  articles.loadById(id).subscribe(new Action1<Article>() {
    @Override
    public void call(final Article article) {

      Subscription s = Subscriptions.from(
          title.bind(article.title),
          authorName.bind(article.author.name),
          authorThumbnailUrl.bind(article.author.thumbnailUrl),
          createdAt.bind(article.createdAt, TIMEAGO),
          contentHtml.bind(article.html())
      );

      add(s);

      authorUrl.set(article.author.url());
      contentUrl.set(article.url());
      tags.addAll(Objects.map(article.tags, tagMapper));

    }
  }, Rx.ERROR_ACTION_EMPTY);
}
 
Example #4
Source File: ArticleAboutFragment.java    From Qiitanium with MIT License 6 votes vote down vote up
@Override
protected Subscription onBind() {
  viewModel = viewModelHolder.get();
  commentListViewModel = CommentListViewModel.create(getContext());
  commentListViewModel.setArticleId(getArticleId());

  return Subscriptions.from(
      commentListViewModel,
      listAdapter.bind(commentListViewModel.items()),
      emptyText.bind(commentListViewModel.isEmpty(), RxActions.setVisibility()),
      progressBar.bind(commentListViewModel.isLoading(), RxActions.setVisibility()),
      authorText.bind(viewModel.authorName(), RxActions.setText()),
      authorImage.bind(viewModel.authorThumbnailUrl(), loadThumbnailAction()),
      tagList.bind(viewModel.tags())
  );
}
 
Example #5
Source File: UnicastDisposableCachingSubject.java    From Prana with Apache License 2.0 6 votes vote down vote up
@Override
public void call(final Subscriber<? super T> subscriber) {
    if (state.casState(State.STATES.UNSUBSCRIBED, State.STATES.SUBSCRIBED)) {

        // drain queued notifications before subscription
        // we do this here before PassThruObserver so the consuming thread can do this before putting itself in
        // the line of the producer
        state.buffer.sendAllNotifications(subscriber);

        // register real observer for pass-thru ... and drain any further events received on first notification
        state.setObserverRef(new PassThruObserver<>(subscriber, state));
        subscriber.add(Subscriptions.create(new Action0() {
            @Override
            public void call() {
                state.setObserverRef(Subscribers.empty());
            }
        }));
    } else if (State.STATES.SUBSCRIBED.ordinal() == state.state) {
        subscriber.onError(new IllegalStateException("Content can only have one subscription. Use Observable.publish() if you want to multicast."));
    } else if (State.STATES.DISPOSED.ordinal() == state.state) {
        subscriber.onError(new IllegalStateException("Content stream is already disposed."));
    }
}
 
Example #6
Source File: MultipleSubscribersHotObs.java    From tutorials with MIT License 6 votes vote down vote up
private static Observable getObservable() {
    return Observable.create(subscriber -> {
        frame.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                subscriber.onNext(e.getX());
            }
        });
        subscriber.add(Subscriptions.create(() -> {
            LOGGER.info("Clear resources");
            for (MouseListener listener : frame.getListeners(MouseListener.class)) {
                frame.removeMouseListener(listener);
            }
        }));
    });
}
 
Example #7
Source File: AbstractSingleToFutureConverterTest.java    From future-converter with Apache License 2.0 6 votes vote down vote up
private Single<String> createAsyncSingle() {
    return Single.create((SingleSubscriber<? super String> subscriber) -> {
        subscribed.incrementAndGet();
        Future<?> future = executorService.submit(() -> {
            try {
                taskStartedLatch.countDown();
                waitLatch.await();
                subscriber.onSuccess(VALUE);
            } catch (InterruptedException e) {
                subscriber.onError(e);
                throw new RuntimeException(e);
            }
        });
        subscriber.add(Subscriptions.from(future));
        assertTrue(this.futureTaskRef.compareAndSet(null, future));
    });
}
 
Example #8
Source File: RxJavaFutureUtils.java    From future-converter with Apache License 2.0 6 votes vote down vote up
private static <T> OnSubscribe<T> onSubscribe(final ValueSource<T> valueSource) {
    return subscriber -> {
        valueSource.addCallbacks(value -> {
                if (!subscriber.isUnsubscribed()) {
                    try {
                        subscriber.onSuccess(value);
                    } catch (Throwable e) {
                        subscriber.onError(e);
                    }
                }
            },
            throwable -> {
                if (!subscriber.isUnsubscribed()) {
                    subscriber.onError(throwable);
                }
            });
        subscriber.add(Subscriptions.create(() -> valueSource.cancel(true)));
    };
}
 
Example #9
Source File: BroadcastObservable.java    From RxSerach with Apache License 2.0 6 votes vote down vote up
private static Subscription unsubscribeInUiThread(final Action0 unsubscribe) {
    return Subscriptions.create(new Action0() {
        @Override public void call() {
            if (Looper.getMainLooper() == Looper.myLooper()) {
                unsubscribe.call();
            } else {
                final Scheduler.Worker inner = AndroidSchedulers.mainThread().createWorker();
                inner.schedule(new Action0() {
                    @Override public void call() {
                        unsubscribe.call();
                        inner.unsubscribe();
                    }
                });
            }
        }
    });
}
 
Example #10
Source File: OnSubscribeBroadcastRegister.java    From rxnetwork-android with Apache License 2.0 6 votes vote down vote up
@Override
public void call(final Subscriber<? super Intent> subscriber) {
    final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            subscriber.onNext(intent);
        }
    };

    final Subscription subscription = Subscriptions.create(new Action0() {
        @Override
        public void call() {
            context.unregisterReceiver(broadcastReceiver);
        }
    });

    subscriber.add(subscription);
    context.registerReceiver(broadcastReceiver, intentFilter, broadcastPermission, schedulerHandler);

}
 
Example #11
Source File: FileObservable.java    From RxFileObserver with Apache License 2.0 6 votes vote down vote up
@Override
public void call(final Subscriber<? super FileEvent> subscriber) {
    final FileObserver observer = new FileObserver(pathToWatch) {
        @Override
        public void onEvent(int event, String file) {
            if(subscriber.isUnsubscribed()) {
                return;
            }

            FileEvent fileEvent = FileEvent.create(event, file);
            subscriber.onNext(fileEvent);

            if(fileEvent.isDeleteSelf()) {
                subscriber.onCompleted();
            }
        }
    };
    observer.startWatching(); //START OBSERVING

    subscriber.add(Subscriptions.create(new Action0() {
        @Override
        public void call() {
            observer.stopWatching();
        }
    }));
}
 
Example #12
Source File: GenericDialogs.java    From aptoide-client-v8 with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Show an AlertDialog with the {@code title} and the {@code message}. The Alert dialog has an
 * "ok" button.
 *
 * @param title Title to apply on AlertDialog
 * @param message Message to asSnack on AlertDialog
 * @param resourceId
 *
 * @return A Observable that shows the dialog when subscribed and return the action made by
 * user. This action is represented by EResponse
 *
 * @see EResponse
 */
public static Observable<EResponse> createGenericOkCancelMessage(Context context, String title,
    String message, int resourceId) {
  return Observable.create((Subscriber<? super EResponse> subscriber) -> {
    final AlertDialog dialog =
        new AlertDialog.Builder(new ContextThemeWrapper(context, resourceId)).setTitle(title)
            .setMessage(message)
            .setPositiveButton(android.R.string.ok, (listener, which) -> {
              subscriber.onNext(EResponse.YES);
              subscriber.onCompleted();
            })
            .setNegativeButton(android.R.string.cancel, (dialogInterface, i) -> {
              subscriber.onNext(EResponse.CANCEL);
              subscriber.onCompleted();
            })
            .create();
    // cleaning up
    subscriber.add(Subscriptions.create(() -> dialog.dismiss()));
    dialog.show();
  });
}
 
Example #13
Source File: GenericDialogs.java    From aptoide-client-v8 with GNU General Public License v3.0 6 votes vote down vote up
public static Observable<EResponse> createGenericOkCancelMessageWithColorButton(Context context,
    String title, String message, String okButton, String cancelButton) {
  return Observable.create((Subscriber<? super EResponse> subscriber) -> {
    final AlertDialog dialog = new AlertDialog.Builder(context).setTitle(title)
        .setMessage(message)
        .setPositiveButton(okButton, (listener, which) -> {
          subscriber.onNext(EResponse.YES);
          subscriber.onCompleted();
        })
        .setNegativeButton(cancelButton, (dialogInterface, i) -> {
          subscriber.onNext(EResponse.CANCEL);
          subscriber.onCompleted();
        })
        .create();
    subscriber.add(Subscriptions.create(() -> dialog.dismiss()));
    dialog.show();
    dialog.getButton(AlertDialog.BUTTON_NEGATIVE)
        .setTextColor(Color.GRAY);
  });
}
 
Example #14
Source File: GenericDialogs.java    From aptoide-client-v8 with GNU General Public License v3.0 6 votes vote down vote up
public static Observable<EResponse> createGenericContinueMessage(Context context,
    @Nullable View view, String title, String message, @StringRes int buttonText,
    int resourceId) {
  return Observable.create((Subscriber<? super EResponse> subscriber) -> {
    AlertDialog.Builder builder =
        new AlertDialog.Builder(new ContextThemeWrapper(context, resourceId)).setTitle(title)
            .setMessage(message)
            .setPositiveButton(buttonText, (dialogInterface, i) -> {
              subscriber.onNext(EResponse.YES);
              subscriber.onCompleted();
            });
    if (view != null) {
      builder.setView(view);
    }
    AlertDialog alertDialog = builder.create();
    subscriber.add(Subscriptions.create(() -> alertDialog.dismiss()));
    alertDialog.show();
  });
}
 
Example #15
Source File: GenericDialogs.java    From aptoide-client-v8 with GNU General Public License v3.0 6 votes vote down vote up
public static Observable<EResponse> createGenericContinueCancelMessage(Context context,
    String title, String message, int resourceId) {
  return Observable.create((Subscriber<? super EResponse> subscriber) -> {
    final AlertDialog ad =
        new AlertDialog.Builder(new ContextThemeWrapper(context, resourceId)).setTitle(title)
            .setMessage(message)
            .setPositiveButton(android.R.string.ok, (dialog, which) -> {
              subscriber.onNext(EResponse.YES);
              subscriber.onCompleted();
            })
            .setNegativeButton(android.R.string.cancel, (dialogInterface, i) -> {
              subscriber.onNext(EResponse.NO);
              subscriber.onCompleted();
            })
            .setOnCancelListener(dialog -> {
              subscriber.onNext(EResponse.CANCEL);
              subscriber.onCompleted();
            })
            .create();
    // cleaning up
    subscriber.add(Subscriptions.create(() -> ad.dismiss()));
    ad.show();
  });
}
 
Example #16
Source File: GenericDialogs.java    From aptoide-client-v8 with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Show an AlertDialog with the {@code title} and the {@code message}. The Alert dialog has an
 * "yes" button and a "no" button.
 *
 * @param title Title to apply on AlertDialog
 * @param message Message to asSnack on AlertDialog
 * @param resourceId
 *
 * @return A Observable that shows the dialog when subscribed and return the action made by
 * user. This action is represented by EResponse
 *
 * @see EResponse
 */
public static Observable<EResponse> createGenericYesNoCancelMessage(@NonNull Context context,
    @Nullable String title, @Nullable String message, int resourceId) {
  return Observable.create((Subscriber<? super EResponse> subscriber) -> {
    final AlertDialog dialog =
        new AlertDialog.Builder(new ContextThemeWrapper(context, resourceId)).setTitle(title)
            .setMessage(message)
            .setPositiveButton(android.R.string.yes, (listener, which) -> {
              subscriber.onNext(EResponse.YES);
              subscriber.onCompleted();
            })
            .setNegativeButton(android.R.string.no, (listener, which) -> {
              subscriber.onNext(EResponse.NO);
              subscriber.onCompleted();
            })
            .setOnCancelListener(listener -> {
              subscriber.onNext(EResponse.CANCEL);
              subscriber.onCompleted();
            })
            .create();
    // cleaning up
    subscriber.add(Subscriptions.create(() -> dialog.dismiss()));
    dialog.show();
  })
      .subscribeOn(AndroidSchedulers.mainThread());
}
 
Example #17
Source File: GenericDialogs.java    From aptoide-client-v8 with GNU General Public License v3.0 6 votes vote down vote up
public static Observable<EResponse> createGenericOkCancelMessage(Context context, String title,
    @StringRes int message, @StringRes int okMessage, @StringRes int cancelMessage,
    int resourceId) {
  return Observable.create((Subscriber<? super EResponse> subscriber) -> {
    final AlertDialog ad =
        new AlertDialog.Builder(new ContextThemeWrapper(context, resourceId)).setTitle(title)
            .setMessage(message)
            .setPositiveButton(okMessage, (dialog, which) -> {
              subscriber.onNext(EResponse.YES);
              subscriber.onCompleted();
            })
            .setNegativeButton(cancelMessage, (dialogInterface, i) -> {
              subscriber.onNext(EResponse.NO);
              subscriber.onCompleted();
            })
            .setOnCancelListener(dialog -> {
              subscriber.onNext(EResponse.CANCEL);
              subscriber.onCompleted();
            })
            .create();
    // cleaning up
    subscriber.add(Subscriptions.create(() -> ad.dismiss()));
    ad.show();
  });
}
 
Example #18
Source File: BroadcastRegisterOnSubscribe.java    From aptoide-client-v8 with GNU General Public License v3.0 6 votes vote down vote up
@Override public void call(final Subscriber<? super Intent> subscriber) {
  final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override public void onReceive(Context context, Intent intent) {
      if (!subscriber.isUnsubscribed()) {
        subscriber.onNext(intent);
      }
    }
  };

  final Subscription subscription = Subscriptions.create(new Action0() {
    @Override public void call() {
      context.unregisterReceiver(broadcastReceiver);
    }
  });

  subscriber.add(subscription);
  context.registerReceiver(broadcastReceiver, intentFilter, broadcastPermission,
      schedulerHandler);
}
 
Example #19
Source File: FirebaseEntityStore.java    From buddysearch with Apache License 2.0 6 votes vote down vote up
private <T> Observable<T> getQuery(Query query, Action2<Subscriber<? super T>, DataSnapshot> onNextAction, boolean subscribeForSingleEvent) {
    return Observable.create(subscriber -> {
        ValueEventListener eventListener = new ValueEventListener() {

            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                onNextAction.call(subscriber, dataSnapshot);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                subscriber.onError(new FirebaseException(databaseError.getMessage()));
            }
        };
        if (subscribeForSingleEvent) {
            query.addListenerForSingleValueEvent(eventListener);
        } else {
            query.addValueEventListener(eventListener);
        }
        subscriber.add(Subscriptions.create(() -> query.removeEventListener(eventListener)));
    });
}
 
Example #20
Source File: Preferences.java    From aptoide-client-v8 with GNU General Public License v3.0 6 votes vote down vote up
private Observable<Void> change(String key) {
  return Observable.create(new Observable.OnSubscribe<Void>() {
    @Override public void call(Subscriber<? super Void> subscriber) {

      final SharedPreferences.OnSharedPreferenceChangeListener listener =
          new SharedPreferences.OnSharedPreferenceChangeListener() {
            @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
                String changedKey) {
              if (!subscriber.isUnsubscribed() && changedKey.equals(key)) {
                subscriber.onNext(null);
              }
            }
          };

      subscriber.add(Subscriptions.create(
          () -> preferences.unregisterOnSharedPreferenceChangeListener(listener)));

      preferences.registerOnSharedPreferenceChangeListener(listener);
    }
  });
}
 
Example #21
Source File: CenterTitleSideButtonBar.java    From HandyWidgets with MIT License 6 votes vote down vote up
private Subscription unsubscribeInUiThread(final Action0 unsubscribe) {
    return Subscriptions.create(new Action0() {

        @Override
        public void call() {
            if (Looper.getMainLooper() == Looper.myLooper()) {
                unsubscribe.call();
            } else {
                final Scheduler.Worker inner = AndroidSchedulers.mainThread().createWorker();
                inner.schedule(new Action0() {
                    @Override
                    public void call() {
                        unsubscribe.call();
                        inner.unsubscribe();
                    }
                });
            }
        }
    });
}
 
Example #22
Source File: ArticleListFragment.java    From Qiitanium with MIT License 5 votes vote down vote up
@Override
protected Subscription onBind() {
  return Subscriptions.from(
      viewModel,
      listAdapter.bind(viewModel.items()),
      progressBar.bind(viewModel.isLoading(), RxActions.setVisibility())
  );
}
 
Example #23
Source File: CoreScheduler.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
@Override
public Subscription schedule(Action0 action, long delayTime, TimeUnit unit) {
    if (isUnsubscribed()) {
        return Subscriptions.unsubscribed();
    }
    ScheduledAction s = poolWorker.scheduleActual(action, delayTime, unit, timed);

    return s;
}
 
Example #24
Source File: AndroidSubscriptions.java    From u2020-mvp with Apache License 2.0 5 votes vote down vote up
/**
 * Create a {@link Subscription} that always runs the specified {@code unsubscribe} on the
 * UI thread.
 */

public static Subscription unsubscribeInUiThread(final Action0 unsubscribe) {
    return Subscriptions.create(() -> {
        if (Looper.getMainLooper() == Looper.myLooper()) {
            unsubscribe.call();
        } else {
            final Scheduler.Worker inner = AndroidSchedulers.mainThread().createWorker();
            inner.schedule(() -> {
                unsubscribe.call();
                inner.unsubscribe();
            });
        }
    });
}
 
Example #25
Source File: QueryUpdateOnSubscribe.java    From rxjava-jdbc with Apache License 2.0 5 votes vote down vote up
private Subscription createUnsubscriptionAction(final State state) {
    return Subscriptions.create(new Action0() {
        @Override
        public void call() {
            close(state);
        }
    });
}
 
Example #26
Source File: QuerySelectOnSubscribe.java    From rxjava-jdbc with Apache License 2.0 5 votes vote down vote up
private static <T> void setupUnsubscription(Subscriber<T> subscriber, final State state) {
    subscriber.add(Subscriptions.create(new Action0() {
        @Override
        public void call() {
            closeQuietly(state);
        }
    }));
}
 
Example #27
Source File: BaseLaunchActivity.java    From satellite with MIT License 5 votes vote down vote up
@Override
protected Subscription onConnect() {
    return Subscriptions.from(super.onConnect(),

        Observable.interval(500, 500, TimeUnit.MILLISECONDS, mainThread())
            .subscribe(ignored -> {
                StringBuilder builder = new StringBuilder();
                builder.append("connections:\n");
                for (String key : ReconnectableMap.INSTANCE.keys())
                    builder.append(key).append("\n");
                TextView report = (TextView)findViewById(R.id.stationReport);
                report.setText(builder.toString());
            }));
}
 
Example #28
Source File: SingleConnectionActivity.java    From satellite with MIT License 5 votes vote down vote up
@Override
protected Subscription onConnect() {
    return Subscriptions.from(super.onConnect(),

        channel(SINGLE_RESTARTABLE_ID, DeliveryMethod.SINGLE, new ExampleSingleObservableFactory())
            .subscribe(RxNotification.split(
                value -> {
                    log("SINGLE: onNext " + value);
                    onNext(value);
                },
                throwable -> log("SINGLE: onError " + throwable))));
}
 
Example #29
Source File: SingleThreadedComputationScheduler.java    From jawampa with Apache License 2.0 5 votes vote down vote up
@Override
public Subscription schedule(Action0 action, long delayTime, TimeUnit unit) {
    if (innerSubscription.isUnsubscribed()) {
        // don't schedule, we are unsubscribed
        return Subscriptions.empty();
    }
    
    ScheduledAction s = (ScheduledAction)innerWorker.schedule(action, delayTime, unit);
    innerSubscription.add(s);
    s.addParent(innerSubscription);
    return s;
}
 
Example #30
Source File: ArticleActivity.java    From Qiitanium with MIT License 5 votes vote down vote up
@Override
protected Subscription onBind() {
  return Subscriptions.from(
      timeAgo.bind(viewModel.createdAt(), RxActions.setText()),
      title.bind(viewModel.title(), RxActions.setText())
  );
}