當前位置: 首頁>>代碼示例>>Java>>正文


Java PublishSubject類代碼示例

本文整理匯總了Java中io.reactivex.subjects.PublishSubject的典型用法代碼示例。如果您正苦於以下問題:Java PublishSubject類的具體用法?Java PublishSubject怎麽用?Java PublishSubject使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


PublishSubject類屬於io.reactivex.subjects包,在下文中一共展示了PublishSubject類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: downloadProducts

import io.reactivex.subjects.PublishSubject; //導入依賴的package包/類
@Override
public void downloadProducts(DownloadProductsRequest request, StreamObserver<Product> responseObserver) {
  PublishSubject<Product> productPublishSubject = PublishSubject.create();
  productPublishSubject
      .doOnNext(product -> {
        responseObserver.onNext(product);
        counter.labels("downloadProducts", "success");
      })
      .doOnComplete(() -> responseObserver.onCompleted())
      .doOnError(t -> {
        responseObserver.onError(t);
        counter.labels("downloadProducts", "failed");
      })
      .subscribe();
  productDao.downloadProducts(request, productPublishSubject);
}
 
開發者ID:email2liyang,項目名稱:grpc-mate,代碼行數:17,代碼來源:ProductReadService.java

示例2: showNameInputDialog

import io.reactivex.subjects.PublishSubject; //導入依賴的package包/類
private Observable<String> showNameInputDialog(String prefix, MaterialDialog.InputCallback textWatcher) {
    final PublishSubject<String> input = PublishSubject.create();
    DialogUtils.showDialog(new ThemeColorMaterialDialogBuilder(mContext).title(R.string.text_name)
            .inputType(InputType.TYPE_CLASS_TEXT)
            .alwaysCallInputCallback()
            .input(getString(R.string.text_please_input_name), prefix, false, textWatcher)
            .onPositive(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    input.onNext(dialog.getInputEditText().getText().toString());
                    input.onComplete();
                }
            })
            .build());
    return input;
}
 
開發者ID:feifadaima,項目名稱:https-github.com-hyb1996-NoRootScriptDroid,代碼行數:17,代碼來源:ScriptOperations.java

示例3: doSomeWork

import io.reactivex.subjects.PublishSubject; //導入依賴的package包/類
/**
 * PublishSubject隻會把在訂閱發生的時間點之後來自原始Observable的數據發射給觀察者。
 * 需要注意的是,PublishSubject可能會一創建完成就立刻開始發射數據(除非你可以阻止它發生),
 * 因此這裏有一個風險:在Subject被創建後到有觀察者訂閱它之前這個時間段內,一個或多個數據可能會丟失。
 * 如果要確保來自原始Observable的所有數據都被分發:
 * 1.使用Create創建那個Observable以便手動給它引入"冷"Observable的行為(當所有觀察者都已經訂閱時才開始發射數據)
 * 2.改用ReplaySubject。
 *
 * 如果原始的Observable因為發生了一個錯誤而終止,PublishSubject將不會發射任何數據,隻是簡單的向前傳遞這個錯誤通知。
 */
private void doSomeWork() {

    PublishSubject<Integer> source = PublishSubject.create();

    source.subscribe(getFirstObserver()); // it will get 1, 2, 3, 4 and onComplete

    source.onNext(1);
    source.onNext(2);
    source.onNext(3);

    /*
     * it will emit 4 and onComplete for second observer also.
     */
    source.subscribe(getSecondObserver());

    source.onNext(4);
    source.onComplete();
}
 
開發者ID:changjiashuai,項目名稱:RxJava2-Android-Sample,代碼行數:29,代碼來源:PublishSubjectExampleActivity.java

示例4: onRequestPermissionsResult

import io.reactivex.subjects.PublishSubject; //導入依賴的package包/類
void onRequestPermissionsResult(String permissions[], int[] grantResults, boolean[] shouldShowRequestPermissionRationale) {
    for (int i = 0, size = permissions.length; i < size; i++) {
        Log.i("","onRequestPermissionsResult  " + permissions[i]);
        // Find the corresponding subject
        PublishSubject<Permission> subject = mSubjects.get(permissions[i]);
        if (subject == null) {
            // No subject found
            Log.e(RxPermissions.TAG, "RxPermissions.onRequestPermissionsResult invoked but didn't find the corresponding permission request.");
            return;
        }
        mSubjects.remove(permissions[i]);
        boolean granted = grantResults[i] == PackageManager.PERMISSION_GRANTED;
        subject.onNext(new Permission(permissions[i], granted, shouldShowRequestPermissionRationale[i]));
        subject.onComplete();
    }
}
 
開發者ID:ChangWeiBa,項目名稱:AesExoPlayer,代碼行數:17,代碼來源:RxPermissionsFragment.java

示例5: monitor

import io.reactivex.subjects.PublishSubject; //導入依賴的package包/類
private void monitor(InputStream input, PublishSubject<String> subject) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(input, encoding));
    final int BUFFERSIZE = 4096;
    char[] buffer = new char[BUFFERSIZE];
    while (true) {
        try {
            if (Thread.interrupted()) {
                subject.onComplete();
                return;
            }
            int read = reader.read(buffer, 0, BUFFERSIZE);
            if (read == -1) {
                subject.onComplete();
                return;
            }

            subject.onNext(new String(buffer, 0, read));
        } catch (IOException e) {
            subject.onError(e);
            return;
        }
    }
}
 
開發者ID:Microsoft,項目名稱:java-debug,代碼行數:24,代碼來源:ProcessConsole.java

示例6: initView

import io.reactivex.subjects.PublishSubject; //導入依賴的package包/類
private void initView() {
        subject = PublishSubject.create();
        subject.debounce(0, TimeUnit.MILLISECONDS)
//                .filter(new Predicate<Float>() {
//                    @Override
//                    public boolean test(Float brightness) throws Exception {
//                        return true;
//                    }
//                })
                .distinctUntilChanged()
                .switchMap(new Function<Float, ObservableSource<ColorMatrixColorFilter>>() {
                    @Override
                    public ObservableSource<ColorMatrixColorFilter> apply(Float value) throws Exception {
                        return postBrightness(value);
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ColorMatrixColorFilter>() {
                    @Override
                    public void accept(ColorMatrixColorFilter colorMatrixColorFilter) throws Exception {
                        setColorFilter(colorMatrixColorFilter);
                    }
                });
    }
 
開發者ID:hoanganhtuan95ptit,項目名稱:EditPhoto,代碼行數:26,代碼來源:BrightnessView.java

示例7: TranscodingServiceImpl

import io.reactivex.subjects.PublishSubject; //導入依賴的package包/類
@Inject
TranscodingServiceImpl(ExternalProcessService externalProcessService,
                       TranscoderSettings transcoderSettings,
                       MediaScanSettings mediaScanSettings,
                       OutputParser parser) {
    this.externalProcessService = externalProcessService;
    this.transcoderSettings = transcoderSettings;
    this.mediaScanSettings = mediaScanSettings;

    this.parser = parser;

    this.publisher = PublishSubject.create().toSerialized();

    publisher.ofType(TranscodeTask.class)
             .skipWhile(o -> isActive())
             .observeOn(Schedulers.computation())
             .subscribeOn(Schedulers.io())
             .subscribe(this::prepareTranscode);
}
 
開發者ID:ccremer,項目名稱:clustercode,代碼行數:20,代碼來源:TranscodingServiceImpl.java

示例8: onCreateView

import io.reactivex.subjects.PublishSubject; //導入依賴的package包/類
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_two_way_data_biding, container, false);
    unbinder = ButterKnife.bind(this, view);

    publishSubject = PublishSubject.create();

    publishSubject.subscribe(new Consumer<String>() {
        @Override
        public void accept(String s) throws Exception {
            mTvAddResult.setText(s);
        }
    });

    onNumChanged();

    mEtAddLeft.requestFocus();

    return view;
}
 
開發者ID:jiangkang,項目名稱:KTools,代碼行數:23,代碼來源:TwoWayDataBidingFragment.java

示例9: onUserQueryEvent_emptyQueryString_shouldDoNothingWithView

import io.reactivex.subjects.PublishSubject; //導入依賴的package包/類
@Test
public void onUserQueryEvent_emptyQueryString_shouldDoNothingWithView() {
  // given
  PublishSubject<UserQueryEvent> userQuery$ = PublishSubject.create();
  UserListPresenter presenter = new UserListPresenter(
      userQuery$,
      userService,
      () -> mock(UserView.class),
      () -> mock(UserPresenter.class),
      DEFAULT_PAGE_SIZE,
      DEFAULT_USER_SEARCH_LIMIT
  );
  presenter.start(view);
  UserQueryEvent event = new UserQueryEvent(" "); // empty string

  // when
  userQuery$.onNext(event);

  // then
  verifyNoMoreInteractions(view, userService);
}
 
開發者ID:xemantic,項目名稱:github-users,代碼行數:22,代碼來源:UserListPresenterTest.java

示例10: onRequestPermissionsResult

import io.reactivex.subjects.PublishSubject; //導入依賴的package包/類
void onRequestPermissionsResult(String permissions[], int[] grantResults, boolean[] shouldShowRequestPermissionRationale) {
    for (int i = 0, size = permissions.length; i < size; i++) {
        log("onRequestPermissionsResult  " + permissions[i]);
        // Find the corresponding subject
        PublishSubject<Permission> subject = mSubjects.get(permissions[i]);
        if (subject == null) {
            // No subject found
            Log.e(RxPermissions.TAG, "RxPermissions.onRequestPermissionsResult invoked but didn't find the corresponding permission request.");
            return;
        }
        mSubjects.remove(permissions[i]);
        boolean granted = (grantResults[i] == PackageManager.PERMISSION_GRANTED) && (PermissionChecker.checkSelfPermission(getContext(), permissions[i]) == PermissionChecker.PERMISSION_GRANTED);
        subject.onNext(new Permission(permissions[i], granted, shouldShowRequestPermissionRationale[i]));
        subject.onComplete();
    }
}
 
開發者ID:CodyyAndroid,項目名稱:RxPermissions,代碼行數:17,代碼來源:RxPermissionsFragment.java

示例11: registerNoThread

import io.reactivex.subjects.PublishSubject; //導入依賴的package包/類
/**
 * 接受消息
 *
 * @param tag      標誌
 * @param callBack 回調
 */
public <T> DisposableObserver registerNoThread(@NonNull final Object tag,
                                               @NonNull final RxBusCallBack<T> callBack) {
    RxBusEvent rxBusEvent = rxBusEventArrayMap.get(tag);
    if (RxUtils.isEmpty(rxBusEvent)) {
        rxBusEvent = new RxBusEvent();
        rxBusEvent.subject = PublishSubject.create().toSerialized();
        rxBusEvent.disposable =
                rxBusEvent.subject
                        .ofType(callBack.busOfType())
                        .subscribeWith(new RxBusObserver<T>() {
                            @Override
                            public void onError(@io.reactivex.annotations.NonNull Throwable e) {
                                super.onError(e);
                                callBack.onBusError(e);
                            }

                            @Override
                            public void onNext(@io.reactivex.annotations.NonNull T t) {
                                super.onNext(t);
                            }
                        });
        rxBusEventArrayMap.put(tag, rxBusEvent);
    }
    return rxBusEvent.disposable;
}
 
開發者ID:7449,項目名稱:RxNetWork,代碼行數:32,代碼來源:RxBus.java

示例12: onUserSelected_view_shouldPostUserSelectedEvent

import io.reactivex.subjects.PublishSubject; //導入依賴的package包/類
@Test
public void onUserSelected_view_shouldPostUserSelectedEvent() {
  // given
  TestObserver<UserSelectedEvent> userSelected$ = TestObserver.create();
  User user = mock(User.class);
  given(user.getLogin()).willReturn("foo");
  PublishSubject<Trigger> userSelectionIntent = PublishSubject.create();
  given(view.userSelection$()).willReturn(userSelectionIntent);

  UserPresenter presenter = new UserPresenter(Sink.of(userSelected$));
  presenter.start(user, view);

  // when
  fire(userSelectionIntent);

  // then
  userSelected$.assertValueCount(1);
  UserSelectedEvent event = userSelected$.values().get(0);
  assertThat(event.getUser().getLogin()).isEqualTo("foo");
}
 
開發者ID:xemantic,項目名稱:github-users,代碼行數:21,代碼來源:UserPresenterTest.java

示例13: refreshOnlineStatus

import io.reactivex.subjects.PublishSubject; //導入依賴的package包/類
public Observable<Boolean> refreshOnlineStatus() {
    PublishSubject<Boolean> online = PublishSubject.create();
    mRetrofit.create(UserApi.class)
            .me()
            .subscribeOn(Schedulers.io())
            .subscribe(user -> {
                setUser(user);
                online.onNext(true);
                online.onComplete();
            }, error -> {
                setUser(null);
                online.onNext(false);
                online.onComplete();
            });
    return online;
}
 
開發者ID:hyb1996,項目名稱:Auto.js,代碼行數:17,代碼來源:UserService.java

示例14: testGetStderrUpdatesEchoesUpdatesFromExecutorObservers

import io.reactivex.subjects.PublishSubject; //導入依賴的package包/類
@Test
public void testGetStderrUpdatesEchoesUpdatesFromExecutorObservers() throws InterruptedException, ExecutionException, TimeoutException {
    final CancelablePromise<JobExecutionResult> executorPromise = new SimpleCancelablePromise<>();
    final Subject<byte[]> stderrSubject = PublishSubject.create();
    final JobExecutor executor =
            MockJobExecutor.thatUses(executorPromise, Observable.just(TestHelpers.generateRandomBytes()), stderrSubject);
    final JobManager jobManager = createManagerWith(executor);

    final Pair<JobId, CancelablePromise<FinalizedJob>> ret =
            jobManager.submit(STANDARD_VALID_REQUEST);

    final Observable<byte[]> stderrObservable =
            jobManager.stderrUpdates(ret.getLeft()).get();

    final AtomicReference<byte[]> bytesFromObservable = new AtomicReference<>();
    stderrObservable.subscribe(bytesFromObservable::set);

    final byte[] bytesExpected = TestHelpers.generateRandomBytes();
    stderrSubject.onNext(bytesExpected);

    executorPromise.complete(new JobExecutionResult(FINISHED));

    ret.getRight().get(DEFAULT_TIMEOUT, MILLISECONDS);

    assertThat(bytesFromObservable.get()).isEqualTo(bytesExpected);
}
 
開發者ID:adamkewley,項目名稱:jobson,代碼行數:27,代碼來源:JobManagerTest.java

示例15: initView

import io.reactivex.subjects.PublishSubject; //導入依賴的package包/類
private void initView() {
        subject = PublishSubject.create();
        subject.debounce(0, TimeUnit.MILLISECONDS)
//                .filter(new Predicate<Float>() {
//                    @Override
//                    public boolean test(Float contrast) throws Exception {
//                        return true;
//                    }
//                })
                .distinctUntilChanged()
                .switchMap(new Function<Float, ObservableSource<ColorMatrixColorFilter>>() {
                    @Override
                    public ObservableSource<ColorMatrixColorFilter> apply(Float value) throws Exception {
                        return postContrast(value);
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ColorMatrixColorFilter>() {
                    @Override
                    public void accept(ColorMatrixColorFilter colorMatrixColorFilter) throws Exception {
                        setColorFilter(colorMatrixColorFilter);
                    }
                });
    }
 
開發者ID:hoanganhtuan95ptit,項目名稱:EditPhoto,代碼行數:26,代碼來源:ContrastView.java


注:本文中的io.reactivex.subjects.PublishSubject類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。