io.reactivex.ObservableEmitter Java Examples

The following examples show how to use io.reactivex.ObservableEmitter. 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: ImageFetcher.java    From Capstone-Project with MIT License 6 votes vote down vote up
public static Observable<Bitmap> getBitmap(final String url) {
    return Observable.create(new ObservableOnSubscribe<Bitmap>() {
        @Override
        public void subscribe(ObservableEmitter<Bitmap> emitter) throws Exception {
            Request request = new Request.Builder()
                    .url(url)
                    .get()
                    .build();

            Response response = OK_HTTP_CLIENT.newCall(request).execute();

            InputStream inputStream = response.body().byteStream();
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            inputStream.close();

            if (bitmap == null) {
                emitter.onError(new NullPointerException("Bitmap fetched from url is null"));
            } else {
                emitter.onNext(bitmap);
            }
            emitter.onNext(bitmap);
        }
    });
}
 
Example #2
Source File: RxPowerAdapter.java    From power-adapters with Apache License 2.0 6 votes vote down vote up
@CheckResult
@NonNull
public static Observable<ChangeEvent> changes(@NonNull final PowerAdapter adapter) {
    checkNotNull(adapter, "adapter");
    return Observable.create(new ObservableOnSubscribe<ChangeEvent>() {
        @Override
        public void subscribe(final ObservableEmitter<ChangeEvent> emitter) throws Exception {
            verifyMainThread();
            final DataObserver dataObserver = new Observer() {
                @Override
                public void onItemRangeChanged(int positionStart, int itemCount, @Nullable Object payload) {
                    emitter.onNext(new ChangeEvent(positionStart, itemCount, payload));
                }
            };
            adapter.registerDataObserver(dataObserver);
            emitter.setDisposable(new MainThreadDisposable() {
                @Override
                protected void onDispose() {
                    adapter.unregisterDataObserver(dataObserver);
                }
            });
        }
    });
}
 
Example #3
Source File: MainActivity.java    From MediaMetadataRetrieverCompat with MIT License 6 votes vote down vote up
private Observable<ThumbnailBitmap> obtainThumbnail(MediaMetadataRetrieverCompat mmrc, int itemCount) {
    //每500毫秒取一帧
    final long interval = 500;
    final int size = getResources().getDimensionPixelSize(R.dimen.thumbnail_size);
    //取帧是耗时的操作,需要放在子线程
    return Observable.create(new ObservableOnSubscribe<ThumbnailBitmap>() {
        @Override
        public void subscribe(@NonNull ObservableEmitter<ThumbnailBitmap> s) throws Exception {
            //异步获取缩略图
            for (int i = 0; i < itemCount; i++) {
                long millis = i * interval;
                Bitmap atTime;
                if (ORIGINAL_SIZE == mSizeType) {
                    atTime = mmrc.getFrameAtTime(millis, mFetchFrameOption);
                } else if (FLOOR_SCALE == mSizeType) {
                    atTime = mmrc.getScaledFrameAtTime(millis, mFetchFrameOption, size, size);
                } else {
                    atTime = mmrc.getCenterCropFrameAtTime(millis, mFetchFrameOption, size, size);
                }
                s.onNext(new ThumbnailBitmap(i, atTime));
            }
            s.onComplete();
        }
    }).subscribeOn(Schedulers.io());
}
 
Example #4
Source File: CompositeBurstNodeService.java    From burstkit4j with Apache License 2.0 6 votes vote down vote up
private synchronized <T> void doIfUsedObservable(ObservableEmitter<T> emitter, AtomicInteger usedObservable, AtomicReferenceArray<Disposable> disposables, int myI, Runnable runnable) {
    int used = usedObservable.get();
    if (used == -1) {
        // We are the first!
        usedObservable.set(myI);
        runnable.run();
        // Kill all of the others.
        Disposable myDisposable = disposables.get(myI);
        disposables.set(myI, null);
        emitter.setCancellable(() -> {
            if (myDisposable != null) {
                myDisposable.dispose();
            }
        }); // Calling this calls the previous one, so all of the others get disposed.
    } else if (used == myI) {
        // We are the used observable.
        runnable.run();
    }
}
 
Example #5
Source File: DecompressionModel.java    From Dainty with Apache License 2.0 6 votes vote down vote up
@Override
public Observable<Long> decompression(final String type, String original, String purpose, boolean deleteZip) {
    final File mInput = new File(original);
    final File mOutput = new File(purpose);
    mProgress = 0L;
    return Observable.create(new ObservableOnSubscribe<Long>() {
        @Override
        public void subscribe(ObservableEmitter<Long> emitter) throws Exception {
            switch (type) {
                case "zip":
                    unzip(mInput, mOutput, emitter);
                    break;
                case "rar":
                    unRar(mInput, mOutput, emitter);
                    break;
                default:
                    emitter.onError(new Throwable("无法解压该类型的压缩文件"));
                    break;
            }
        }
    }).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread());
}
 
Example #6
Source File: LoginRegisterModel.java    From Dainty with Apache License 2.0 6 votes vote down vote up
@Override
public Observable<String> login(final String account, final String oldPassword) {
    return Observable.create(new ObservableOnSubscribe<String>() {
        @Override
        public void subscribe(ObservableEmitter<String> emitter) throws Exception {
            String path = "http://36078d58.nat123.cc/AndroidRegisterAndLogin_war/login";
            Map<String, String> params = new HashMap<>();
            params.put("username", account);
            params.put("password", oldPassword);

            ResponseBody responseBody=executeHttp(path,params);
            if (responseBody != null) {
                String result = responseBody.string().replaceAll("(\\\r\\\n|\\\r|\\\n|\\\n\\\r)", "");
                emitter.onNext(result);
                responseBody.close();
            } else {
                emitter.onError(new Throwable("响应体为空"));
            }
        }
    }).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread());
}
 
Example #7
Source File: RxPermissions.java    From RuntimePermission with Apache License 2.0 6 votes vote down vote up
public Observable<PermissionResult> request(final List<String> permissions) {
    return Observable.create(new ObservableOnSubscribe<PermissionResult>() {
        @Override
        public void subscribe(final ObservableEmitter<PermissionResult> emitter) throws Exception {
            runtimePermission
                    .request(permissions)
                    .onResponse(new ResponseCallback() {
                        @Override
                        public void onResponse(PermissionResult result) {
                            if (result.isAccepted()) {
                                emitter.onNext(result);
                                emitter.onComplete();
                            } else {
                                emitter.onError(new Error(result));
                            }
                        }
                    }).ask();
        }
    });
}
 
Example #8
Source File: RxBeacon.java    From RxBeacon with Apache License 2.0 6 votes vote down vote up
public Observable<RxBeaconRange> beaconsInRegion() {
    return startup()
            .flatMap(new Function<Boolean, ObservableSource<RxBeaconRange>>() {
                @Override
                public ObservableSource<RxBeaconRange> apply(@NonNull Boolean aBoolean) throws Exception {
                    return Observable.create(new ObservableOnSubscribe<RxBeaconRange>() {
                        @Override
                        public void subscribe(@NonNull final ObservableEmitter<RxBeaconRange> objectObservableEmitter) throws Exception {
                            beaconManager.addRangeNotifier(new RangeNotifier() {
                                @Override
                                public void didRangeBeaconsInRegion(Collection<Beacon> collection, Region region) {
                                    objectObservableEmitter.onNext(new RxBeaconRange(collection, region));
                                }
                            });
                            beaconManager.startRangingBeaconsInRegion(getRegion());
                        }
                    });
                }
            });
}
 
Example #9
Source File: ChapterTwo.java    From RxJava2Demo with Apache License 2.0 6 votes vote down vote up
public static void demo1() {
    Observable<Integer> observable = Observable.create(new ObservableOnSubscribe<Integer>() {
        @Override
        public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
            Log.d(TAG, "Observable thread is : " + Thread.currentThread().getName());
            Log.d(TAG, "emit 1");
            emitter.onNext(1);
        }
    });

    Consumer<Integer> consumer = new Consumer<Integer>() {
        @Override
        public void accept(Integer integer) throws Exception {
            Log.d(TAG, "Observer thread is :" + Thread.currentThread().getName());
            Log.d(TAG, "onNext: " + integer);
        }
    };

    observable.subscribe(consumer);
}
 
Example #10
Source File: RxGps.java    From RxGps with Apache License 2.0 6 votes vote down vote up
private Observable<Boolean> checkPlayServicesAvailable() {
    return Observable.create(new ObservableOnSubscribe<Boolean>() {
        @Override
        public void subscribe(ObservableEmitter<Boolean> e) throws Exception {
            final Activity activity = activityReference.get();
            if (activity != null) {
                final GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
                final int status = apiAvailability.isGooglePlayServicesAvailable(activity);

                if (status != ConnectionResult.SUCCESS) {
                    e.onError(new PlayServicesNotAvailableException());
                } else {
                    e.onNext(true);
                    e.onComplete();
                }
            }
        }
    });
}
 
Example #11
Source File: Rx2Apollo.java    From apollo-android with MIT License 6 votes vote down vote up
/**
 * Converts an {@link ApolloQueryWatcher} to an asynchronous Observable.
 *
 * @param watcher the ApolloQueryWatcher to convert.
 * @param <T>     the value type
 * @return the converted Observable
 * @throws NullPointerException if watcher == null
 */
@NotNull
@CheckReturnValue
public static <T> Observable<Response<T>> from(@NotNull final ApolloQueryWatcher<T> watcher) {
  checkNotNull(watcher, "watcher == null");
  return Observable.create(new ObservableOnSubscribe<Response<T>>() {
    @Override public void subscribe(final ObservableEmitter<Response<T>> emitter) throws Exception {
      cancelOnObservableDisposed(emitter, watcher);

      watcher.enqueueAndWatch(new ApolloCall.Callback<T>() {
        @Override public void onResponse(@NotNull Response<T> response) {
          if (!emitter.isDisposed()) {
            emitter.onNext(response);
          }
        }

        @Override public void onFailure(@NotNull ApolloException e) {
          Exceptions.throwIfFatal(e);
          if (!emitter.isDisposed()) {
            emitter.onError(e);
          }
        }
      });
    }
  });
}
 
Example #12
Source File: LocationRepository.java    From Nibo with MIT License 6 votes vote down vote up
@Override
public Observable<Location> getLocationObservable() {
    return Observable.create(new ObservableOnSubscribe<Location>() {
        @Override
        public void subscribe(final ObservableEmitter<Location> source) throws Exception {
            FusedLocationProviderClient locationClient = LocationServices.getFusedLocationProviderClient(context);
            locationClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    if (location != null) {
                        source.onNext(location);
                    }
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    source.onError(e);
                }
            });
        }
    }).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread());
}
 
Example #13
Source File: ReadTadPagePresenter.java    From GankGirl with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void subscribe(ObservableEmitter<List<ReadTypeBean>> subscriber) throws Exception {
    List<ReadTypeBean> datas = new ArrayList<>();
    try {
        Document doc = Jsoup.connect(Constants.API_URL_READ).get();
        Elements tads = doc.select("div#xiandu_cat").select("a");
        for (Element tad : tads) {
            ReadTypeBean bean = new ReadTypeBean();
            bean.setTitle(tad.text());//获取标题
            bean.setUrl(tad.absUrl("href"));//absUrl可以获取地址的绝对路径
            datas.add(bean);
            Log.v("Jsoup","title= "+bean.getTitle()+"   url= "+bean.getUrl());
        }
    } catch (IOException e) {
        subscriber.onError(e);
    }

    subscriber.onNext(datas);
    subscriber.onComplete();
}
 
Example #14
Source File: RxBus.java    From AndroidWallet with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 根据传递的 eventType 类型返回特定类型(eventType)的 被观察者
 */
public <T> Observable<T> toObservableSticky(final Class<T> eventType) {
    synchronized (mStickyEventMap) {
        Observable<T> observable = mBus.ofType(eventType);
        final Object event = mStickyEventMap.get(eventType);

        if (event != null) {
            return Observable.merge(observable, Observable.create(new ObservableOnSubscribe<T>() {
                @Override
                public void subscribe(ObservableEmitter<T> emitter) throws Exception {
                    emitter.onNext(eventType.cast(event));
                }
            }));
        } else {
            return observable;
        }
    }
}
 
Example #15
Source File: AppStateObservableOnSubscribe.java    From RxAppState with MIT License 6 votes vote down vote up
@Override
public void subscribe(@NonNull final ObservableEmitter<AppState> appStateEmitter) throws Exception {
  final AppStateListener appStateListener = new AppStateListener() {
    @Override
    public void onAppDidEnterForeground() {
      appStateEmitter.onNext(FOREGROUND);
    }

    @Override
    public void onAppDidEnterBackground() {
      appStateEmitter.onNext(BACKGROUND);
    }
  };

  appStateEmitter.setCancellable(new Cancellable() {
    @Override public void cancel() throws Exception {
      recognizer.removeListener(appStateListener);
      recognizer.stop();
    }
  });

  recognizer.addListener(appStateListener);
  recognizer.start();
}
 
Example #16
Source File: ChapterThree.java    From RxJava2Demo with Apache License 2.0 6 votes vote down vote up
public static void demo3() {
    Observable.create(new ObservableOnSubscribe<Integer>() {
        @Override
        public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
            emitter.onNext(1);
            emitter.onNext(2);
            emitter.onNext(3);
        }
    }).concatMap(new Function<Integer, ObservableSource<String>>() {
        @Override
        public ObservableSource<String> apply(Integer integer) throws Exception {
            final List<String> list = new ArrayList<>();
            for (int i = 0; i < 3; i++) {
                list.add("I am value " + integer);
            }
            return Observable.fromIterable(list).delay(10, TimeUnit.MILLISECONDS);
        }
    }).subscribe(new Consumer<String>() {
        @Override
        public void accept(String s) throws Exception {
            Log.d(TAG, s);
        }
    });
}
 
Example #17
Source File: Helper.java    From AppOpsX with MIT License 6 votes vote down vote up
public static Observable<OpsResult> setMode(final Context context, final String pkgName,
    final OpEntryInfo opEntryInfo) {

  return Observable.create(new ObservableOnSubscribe<OpsResult>() {
    @Override
    public void subscribe(ObservableEmitter<OpsResult> e) throws Exception {

      OpsResult opsForPackage = AppOpsx.getInstance(context)
          .setOpsMode(pkgName, opEntryInfo.opEntry.getOp(), opEntryInfo.mode);
      if (opsForPackage != null) {
        if (opsForPackage.getException() == null) {
          e.onNext(opsForPackage);
        } else {
          throw new Exception(opsForPackage.getException());
        }
      }
      e.onComplete();

    }
  }).retry(5, new Predicate<Throwable>() {
    @Override
    public boolean test(Throwable throwable) throws Exception {
      return throwable instanceof IOException || throwable instanceof NullPointerException;
    }
  });
}
 
Example #18
Source File: RxActionDelegate.java    From pandroid with Apache License 2.0 6 votes vote down vote up
public static <T> Observable<Result<T>> observableWrapped(final OnSubscribeAction<T> subscribe) {
    return Observable.<Result<T>>create(new ObservableOnSubscribe<Result<T>>() {
        @Override
        public void subscribe(final ObservableEmitter<Result<T>> emitter) throws Exception {
            final RxActionDelegate<T> delegate = new RxActionDelegate<>(new ActionDelegate<T>() {
                @Override
                public void onSuccess(T result) {
                    emitter.onNext(new Result<T>(result));
                }

                @Override
                public void onError(Exception e) {
                    emitter.onNext(new Result<T>(e));
                }
            });
            emitter.setDisposable(delegate);
            subscribe.subscribe(delegate);
        }
    });
}
 
Example #19
Source File: FirestoreDocumentOnSubscribe.java    From Track-My-Location with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void subscribe(ObservableEmitter<DocumentSnapshot> e) throws Exception {
    DocEventListener listener = new DocEventListener(e);
    ListenerRegistration registration = mDocumentReference.addSnapshotListener(listener);
    e.setDisposable(new Disposable() {
        boolean disposed = false;
        @Override
        public void dispose() {
            if (!isDisposed()) {
                registration.remove();
                listener.emitter = null;
                disposed = true;
            }
        }

        @Override
        public boolean isDisposed() {
            return disposed;
        }
    });
}
 
Example #20
Source File: ConnectOperation.java    From RxAndroidBle with Apache License 2.0 6 votes vote down vote up
@Override
protected void protectedRun(final ObservableEmitter<BluetoothGatt> emitter, final QueueReleaseInterface queueReleaseInterface) {
    final Action queueReleaseAction = new Action() {
        @Override
        public void run() {
            queueReleaseInterface.release();
        }
    };
    final DisposableSingleObserver<BluetoothGatt> disposableGattObserver = getConnectedBluetoothGatt()
            .compose(wrapWithTimeoutWhenNotAutoconnecting())
            // when there are no subscribers there is no point of continuing work -> next will be disconnect operation
            .doFinally(queueReleaseAction)
            .subscribeWith(disposableSingleObserverFromEmitter(emitter));
    emitter.setDisposable(disposableGattObserver);

    if (autoConnect) {
        // with autoConnect the connection may be established after a really long time
        queueReleaseInterface.release();
    }
}
 
Example #21
Source File: HeadSettingActivity.java    From YiZhi with Apache License 2.0 6 votes vote down vote up
@OnClick({R.id.tv_cancel, R.id.tv_ok})
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.tv_cancel:
            onBackPressedSupport();
            break;
        case R.id.tv_ok:
            Observable.create(new ObservableOnSubscribe<Uri>() {
                @Override
                public void subscribe(ObservableEmitter<Uri> e) throws
                        Exception {
                    e.onNext(generateUri());
                    e.onComplete();
                }
            }).compose(RxHelper.<Uri>rxSchedulerHelper())
                    .subscribe(new Consumer<Uri>() {
                        @Override
                        public void accept(Uri uri) throws Exception {
                            RxEventHeadBean rxEventHeadBean = new RxEventHeadBean(uri);
                            RxBus.get().send(RX_BUS_CODE_HEAD_IMAGE_URI, rxEventHeadBean);
                            onBackPressedSupport();
                        }
                    });
            break;
    }
}
 
Example #22
Source File: AesDecryptionObservable.java    From RxFingerprint with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
protected CryptoObject initCryptoObject(ObservableEmitter<FingerprintDecryptionResult> subscriber) {
	try {
		CryptoData cryptoData = CryptoData.fromString(encodingProvider, encryptedString);
		Cipher cipher = cipherProvider.getCipherForDecryption(cryptoData.getIv());
		return new CryptoObject(cipher);
	} catch (Exception e) {
		subscriber.onError(e);
		return null;
	}
}
 
Example #23
Source File: LocalChatBDRealmManager.java    From LazyRecyclerAdapter with MIT License 5 votes vote down vote up
private Observable<Realm> getRealm() {
    return Observable.create(new ObservableOnSubscribe<Realm>() {
        @Override
        public void subscribe(final ObservableEmitter<Realm> emitter)
                throws Exception {
            final Realm observableRealm = Realm.getDefaultInstance();
            emitter.onNext(observableRealm);
            emitter.onComplete();
        }
    });
}
 
Example #24
Source File: ListDirObservable.java    From edslite with GNU General Public License v2.0 5 votes vote down vote up
private static void emitFile(FSRecord f, ObservableEmitter<CachedPathInfo> observableEmitter) throws IOException
{
    CachedPathInfo cpi = new CachedPathInfoBase();
    cpi.init(f.getPath());
    observableEmitter.onNext(cpi);
    observableEmitter.onComplete();
}
 
Example #25
Source File: StockTickerPublisher.java    From graphql-java-subscription-example with MIT License 5 votes vote down vote up
private Runnable newStockTick(ObservableEmitter<StockPriceUpdate> emitter) {
    return () -> {
        List<StockPriceUpdate> stockPriceUpdates = getUpdates(rollDice(0, 5));
        if (stockPriceUpdates != null) {
            emitStocks(emitter, stockPriceUpdates);
        }
    };
}
 
Example #26
Source File: TaskRxJavaFragment.java    From AndroidQuick with MIT License 5 votes vote down vote up
private void noResult() {
    Observable.create(new ObservableOnSubscribe<String>() {
        @Override
        public void subscribe(ObservableEmitter emitter) throws Exception {
            Thread.sleep(5000);
            LogUtil.i(TAG,"[create] the thread has slept 5s, the current thread is " + Thread.currentThread().getName());
            emitter.onNext("the thread has slept 5s");
        }
    })
            .subscribeOn(Schedulers.io())
            .subscribe(new Observer<String>() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(String s) {
                    LogUtil.i(TAG,"[onNext]the current thread is " + Thread.currentThread().getName());
                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            });
}
 
Example #27
Source File: StoreOnSubscribe.java    From grox with Apache License 2.0 5 votes vote down vote up
@Override
public void subscribe(ObservableEmitter<STATE> emitter) throws Exception {

  //the internal listener to the store.
  Store.StateChangeListener<STATE> listener =
      emitter::onNext;
  emitter.setCancellable(() -> store.unsubscribe(listener));
  store.subscribe(listener);
}
 
Example #28
Source File: TaskRxJavaFragment.java    From AndroidQuick with MIT License 5 votes vote down vote up
private void withResult() {
    Observable.create(new ObservableOnSubscribe<String>() {
        @Override
        public void subscribe(ObservableEmitter emitter) throws Exception {
            Thread.sleep(5000);
            LogUtil.i(TAG,"[create] the thread has slept 5s, the current thread is " + Thread.currentThread().getName());
            emitter.onNext("the thread has slept 5s");
        }
    })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<String>() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(String s) {
                    LogUtil.i(TAG,"[onNext]the current thread is " + Thread.currentThread().getName());
                    ToastUtil.showToast(s);
                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            });
}
 
Example #29
Source File: ZhihuModel.java    From YiZhi with Apache License 2.0 5 votes vote down vote up
@Override
public Observable<Boolean> recordItemIsRead(final String key) {
    return Observable.create(new ObservableOnSubscribe<Boolean>() {
        @Override
        public void subscribe(ObservableEmitter<Boolean> emitter) throws Exception {
            emitter.onNext(DBUtils.getDB(AppUtils.getContext()).insertRead(DBConfig
                    .TABLE_ZHIHU, key, ItemState.STATE_IS_READ));
            emitter.onComplete();
        }
    }).compose(RxHelper.<Boolean>rxSchedulerHelper());
}
 
Example #30
Source File: FeatureControllerOnSubscribe.java    From FeatureAdapter with Apache License 2.0 5 votes vote down vote up
@Override
public void subscribe(final ObservableEmitter<FeatureEvent> subscriber) {
  verifyMainThread();

  FeatureEventListener listener =
      event -> {
        if (!subscriber.isDisposed()) {
          subscriber.onNext(event);
        }
      };

  subscriber.setCancellable(() -> featureController.removeFeatureEventListener(listener));

  featureController.addFeatureEventListener(listener);
}