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


Java Subject類代碼示例

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


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

示例1: main

import io.reactivex.subjects.Subject; //導入依賴的package包/類
public static void main(String[] args) {
    Subject<String> subject =
            AsyncSubject.create();
    subject.subscribe(s ->
                    System.out.println("Observer 1: " + s),
            Throwable::printStackTrace,
            () -> System.out.println("Observer 1 done!")
    );
    subject.onNext("Alpha");
    subject.onNext("Beta");
    subject.onNext("Gamma");
    subject.onComplete();
    subject.subscribe(s ->
                    System.out.println("Observer 2: " + s),
            Throwable::printStackTrace,
            () -> System.out.println("Observer 2 done!")
    );
}
 
開發者ID:PacktPublishing,項目名稱:Learning-RxJava,代碼行數:19,代碼來源:Ch5_25.java

示例2: main

import io.reactivex.subjects.Subject; //導入依賴的package包/類
public static void main(String[] args) {
        Subject<String> subject =
                UnicastSubject.create();
        Observable.interval(300, TimeUnit.MILLISECONDS)
                .map(l -> ((l + 1) * 300) + " milliseconds")
                .subscribe(subject);
        sleep(2000);
//multicast to support multiple Observers
        Observable<String> multicast =
                subject.publish().autoConnect();
//bring in first Observer
        multicast.subscribe(s -> System.out.println("Observer 1: "
                + s));
        sleep(2000);
//bring in second Observer
        multicast.subscribe(s -> System.out.println("Observer 2: "
                + s));
        sleep(1000);
    }
 
開發者ID:PacktPublishing,項目名稱:Learning-RxJava,代碼行數:20,代碼來源:Ch5_27.java

示例3: unregister

import io.reactivex.subjects.Subject; //導入依賴的package包/類
/**
 * 取消監聽
 *
 * @param tag
 * @param observable
 * @return
 */
@SuppressWarnings("rawtypes")
public RxBus unregister(@NonNull Object tag,
                        @NonNull Observable<?> observable) {
    if (null == observable)
        return getInstance();
    List<Subject> subjects = subjectMapper.get(tag);
    if (null != subjects) {
        subjects.remove( observable);
        if (isEmpty(subjects)) {
            subjectMapper.remove(tag);
            LogUtils.debugInfo("unregister"+ tag + "  size:" + subjects.size());
        }
    }
    return getInstance();
}
 
開發者ID:Superingxz,項目名稱:MoligyMvpArms,代碼行數:23,代碼來源:RxBus.java

示例4: unregister

import io.reactivex.subjects.Subject; //導入依賴的package包/類
/**
 * 取消訂閱
 *
 * @param tag 標誌
 * @return true 取消成功
 */
public boolean unregister(@NonNull Object tag) {
    RxBusEvent rxBusEvent = rxBusEventArrayMap.get(tag);
    if (RxUtils.isEmpty(rxBusEvent)) {
        return true;
    }
    Subject<Object> subject = rxBusEvent.subject;
    Disposable disposable = rxBusEvent.disposable;
    if (!disposable.isDisposed()) {
        disposable.dispose();
    }
    if (!subject.hasObservers()) {
        rxBusEventArrayMap.remove(tag);
        return true;
    }
    return false;
}
 
開發者ID:7449,項目名稱:RxNetWork,代碼行數:23,代碼來源:RxBus.java

示例5: ClusterMigrationListener

import io.reactivex.subjects.Subject; //導入依賴的package包/類
public ClusterMigrationListener() {
    // init a publish subject, to allow emitting migration events
    Subject<MigrationEvent> subj = PublishSubject.create();
    migrationEvent = subj.toSerialized();

    // collect migration events every 10 seconds and remove any redundant tasks on every node
    migrationEvent.buffer(10, TimeUnit.SECONDS)
            // filter our windows when no events have been observed
            .filter(events -> !events.isEmpty())

            // log partition migration event
            .doOnNext(events -> logger.info("[CLUSTER] Migrated {} partition", events.size()))

            // and update tasks
            .doOnNext(events -> updateTasksAfterClusterEvent())

            // process async
            .subscribeOn(Schedulers.computation())
            .subscribe();
}
 
開發者ID:salesforce,項目名稱:pyplyn,代碼行數:21,代碼來源:ConfigurationUpdateManager.java

示例6: testPersistStdoutReturnsADisposableThatStopsFurtherReads

import io.reactivex.subjects.Subject; //導入依賴的package包/類
@Test
public void testPersistStdoutReturnsADisposableThatStopsFurtherReads() {
    final JobDAO dao = getInstance();
    final JobId jobId = dao.persist(STANDARD_VALID_REQUEST).getId();
    final Subject<byte[]> stdoutSubject = PublishSubject.create();
    final AtomicBoolean stdoutObsWasRead = new AtomicBoolean(false);
    final Observable<byte[]> stdoutObs = stdoutSubject.map(data -> {
        stdoutObsWasRead.set(true);
        return data;
    });

    final Disposable disposable = dao.appendStdout(jobId, stdoutObs);
    disposable.dispose();
    stdoutSubject.onNext(TestHelpers.generateRandomBytes());

    assertThat(stdoutObsWasRead.get());
}
 
開發者ID:adamkewley,項目名稱:jobson,代碼行數:18,代碼來源:JobsDAOTest.java

示例7: testPersistStderrReturnsADisposableThatStopsFurtherReads

import io.reactivex.subjects.Subject; //導入依賴的package包/類
@Test
public void testPersistStderrReturnsADisposableThatStopsFurtherReads() {
    final JobDAO dao = getInstance();
    final JobId jobId = dao.persist(STANDARD_VALID_REQUEST).getId();
    final Subject<byte[]> stderrSubject = PublishSubject.create();
    final AtomicBoolean stderrObsWasRead = new AtomicBoolean(false);
    final Observable<byte[]> stderrObs = stderrSubject.map(data -> {
        stderrObsWasRead.set(true);
        return data;
    });

    final Disposable disposable = dao.appendStderr(jobId, stderrObs);
    disposable.dispose();
    stderrSubject.onNext(TestHelpers.generateRandomBytes());

    assertThat(stderrObsWasRead.get());
}
 
開發者ID:adamkewley,項目名稱:jobson,代碼行數:18,代碼來源:JobsDAOTest.java

示例8: testExecuteStdoutListenerIsCalledWithCompletedOnceApplicationExecutionEnds

import io.reactivex.subjects.Subject; //導入依賴的package包/類
@Test
public void testExecuteStdoutListenerIsCalledWithCompletedOnceApplicationExecutionEnds() throws Throwable {
    final JobExecutor jobExecutor = getInstance();
    final AtomicBoolean completedCalled = new AtomicBoolean(false);
    final Subject<byte[]> stdoutSubject = PublishSubject.create();
    stdoutSubject.doOnComplete(() -> completedCalled.set(true)).subscribe();
    final JobEventListeners listeners = createStdoutListener(stdoutSubject);
    final CancelablePromise<JobExecutionResult> ret =
            jobExecutor.execute(STANDARD_REQUEST, listeners);

    promiseAssert(ret, result -> {
        try {
            // The stdout thread can race with the exit thread
            Thread.sleep(50);
            assertThat(completedCalled.get()).isTrue();
        } catch (InterruptedException ignored) {}
    });
}
 
開發者ID:adamkewley,項目名稱:jobson,代碼行數:19,代碼來源:JobExecutorTest.java

示例9: testExecuteStderrListenerIsCompletedOnceApplicationExecutionEnds

import io.reactivex.subjects.Subject; //導入依賴的package包/類
@Test
public void testExecuteStderrListenerIsCompletedOnceApplicationExecutionEnds() throws Throwable {
    final JobExecutor jobExecutor = getInstance();
    final AtomicBoolean completedCalled = new AtomicBoolean(false);
    final Subject<byte[]> stderrSubject = PublishSubject.create();
    stderrSubject.doOnComplete(() -> completedCalled.set(true)).subscribe();
    final JobEventListeners listeners = createStderrListener(stderrSubject);
    final CancelablePromise<JobExecutionResult> ret =
            jobExecutor.execute(STANDARD_REQUEST, listeners);

    promiseAssert(ret, result -> {
        try {
            // The stderr thread can race with the exit thread
            Thread.sleep(50);
            assertThat(completedCalled.get()).isTrue();
        } catch (InterruptedException ignored) {}
    });
}
 
開發者ID:adamkewley,項目名稱:jobson,代碼行數:19,代碼來源:JobExecutorTest.java

示例10: testExecuteEvaluatesJobInputsAsExpected

import io.reactivex.subjects.Subject; //導入依賴的package包/類
@Test
public void testExecuteEvaluatesJobInputsAsExpected() throws InterruptedException {
    final JobExecutor jobExecutor = getInstance();
    final PersistedJob req =
            standardRequestWithCommand("echo", "${inputs.foo}");
    final AtomicReference<byte[]> bytesEchoedToStdout = new AtomicReference<>(new byte[]{});
    final Subject<byte[]> stdoutSubject = PublishSubject.create();

    stdoutSubject.subscribe(bytes ->
            bytesEchoedToStdout.getAndUpdate(existingBytes ->
                    Bytes.concat(existingBytes, bytes)));

    final Semaphore s = new Semaphore(1);
    s.acquire();
    stdoutSubject.doOnComplete(s::release).subscribe();

    final JobEventListeners listeners =
            createStdoutListener(stdoutSubject);

    jobExecutor.execute(req, listeners);

    s.tryAcquire(TestConstants.DEFAULT_TIMEOUT, MILLISECONDS);

    final String stringFromStdout = new String(bytesEchoedToStdout.get()).trim();
    assertThat(stringFromStdout).isEqualTo("a"); // from spec
}
 
開發者ID:adamkewley,項目名稱:jobson,代碼行數:27,代碼來源:JobExecutorTest.java

示例11: testGetStdoutUpdatesEchoesUpdatesFromExecutorObservers

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

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

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

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

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

    executorPromise.complete(new JobExecutionResult(FINISHED));

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

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

示例12: testGetStderrUpdatesEchoesUpdatesFromExecutorObservers

import io.reactivex.subjects.Subject; //導入依賴的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

示例13: demo2

import io.reactivex.subjects.Subject; //導入依賴的package包/類
private static void demo2() {
    Subject<Long> subject = PublishSubject.create();

    Observable.interval(2, TimeUnit.SECONDS)
            .take(3)
            .doOnComplete(() -> log("Origin-One-doOnComplete"))
            .subscribe(subject);

    Observable.interval(1, TimeUnit.SECONDS)
            .take(2)
            .doOnComplete(() -> log("Origin-Two-doOnComplete"))
            .subscribe(subject);

    subject
            .doOnComplete(() -> log("First-doOnComplete"))
            .subscribe(v -> log(v));
}
 
開發者ID:PacktPublishing,項目名稱:Reactive-Android-Programming,代碼行數:18,代碼來源:Sandbox.java

示例14: demo1

import io.reactivex.subjects.Subject; //導入依賴的package包/類
private static void demo1() throws InterruptedException {
    Subject<Long> subject = PublishSubject.create();

    Observable.interval(2, TimeUnit.SECONDS)
            .take(5)
            .doOnSubscribe((d) -> log("Original-doOnSubscribe"))
            .doOnComplete(() -> log("Original-doOnComplete"))
            .subscribe(subject);

    subject
            .doOnSubscribe((d) -> log("First-doOnSubscribe"))
            .doOnComplete(() -> log("First-doOnComplete"))
            .subscribe(v -> log("First: " + v));

    Thread.sleep(4100);

    subject
            .doOnSubscribe((d) -> log("Second-doOnSubscribe"))
            .doOnComplete(() -> log("Second-doOnComplete"))
            .subscribe(v -> log("Second: " + v));

}
 
開發者ID:PacktPublishing,項目名稱:Reactive-Android-Programming,代碼行數:23,代碼來源:Sandbox.java

示例15: revokeToken

import io.reactivex.subjects.Subject; //導入依賴的package包/類
private Observable<JsonElement> revokeToken(AuthToken token, String clientSecret) {
    // this complexity exists because the access token must be revoked AFTER the refresh token
    // why? because the access token is needed for both revocations!
    Subject<JsonElement> responses = PublishSubject.create();
    RevokeReqBody refreshReqBody = RevokeReqBody.fromRefreshToken(
            token.getRefreshToken(), clientSecret);
    revokeSingleToken(token.getAuthHeader(), refreshReqBody, responses)
            .doOnComplete(() -> {
                RevokeReqBody accessReqBody = RevokeReqBody.fromAccessToken(
                        token.getAccessToken(), clientSecret);
                revokeSingleToken(token.getAuthHeader(), accessReqBody, responses)
                        .subscribe();
            })
            .subscribe();
    return responses;
}
 
開發者ID:TryGhost,項目名稱:Ghost-Android,代碼行數:17,代碼來源:AuthService.java


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