io.reactivex.subjects.Subject Java Examples

The following examples show how to use io.reactivex.subjects.Subject. 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: JobManagerTest.java    From jobson with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #2
Source File: AuthService.java    From quill with MIT License 6 votes vote down vote up
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;
}
 
Example #3
Source File: Sandbox.java    From Reactive-Android-Programming with MIT License 6 votes vote down vote up
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));

}
 
Example #4
Source File: JobExecutorTest.java    From jobson with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteEvaluatesOutputDirAsExpected() throws InterruptedException {
    final JobExecutor jobExecutor = getInstance();
    final PersistedJob req =
            standardRequestWithCommand("echo", "${outputDir}");
    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(Files.exists(Paths.get(stringFromStdout)));
}
 
Example #5
Source File: JobExecutorTest.java    From jobson with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteEvaluatesToStringAsExpected() throws InterruptedException {
    final JobExecutor jobExecutor = getInstance();
    final PersistedJob req =
            standardRequestWithCommand("echo", "${toString(inputs.someString)}");
    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("hello, world!"); // from input fixture
}
 
Example #6
Source File: JobExecutorTest.java    From jobson with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteEvaluatesJoinAsExpected() throws InterruptedException {
    final JobExecutor jobExecutor = getInstance();
    final PersistedJob req =
            standardRequestWithCommand("echo", "${join(',', inputs.someList)}");
    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,b,c,d"); // From the input fixture
}
 
Example #7
Source File: JobsDAOTest.java    From jobson with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #8
Source File: JobExecutorTest.java    From jobson with Apache License 2.0 6 votes vote down vote up
@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
}
 
Example #9
Source File: JobExecutorTest.java    From jobson with Apache License 2.0 6 votes vote down vote up
@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) {}
    });
}
 
Example #10
Source File: Sandbox.java    From Reactive-Android-Programming with MIT License 6 votes vote down vote up
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));
}
 
Example #11
Source File: RxBus.java    From Toutiao with Apache License 2.0 5 votes vote down vote up
@NonNull
public <T> Observable<T> register(@NonNull Object tag) {
    List<Subject> subjectList = subjectMapper.get(tag);
    if (null == subjectList) {
        subjectList = new ArrayList<>();
        subjectMapper.put(tag, subjectList);
    }

    Subject<T> subject = PublishSubject.create();
    subjectList.add(subject);

    //System.out.println("注册到rxbus");
    return subject;
}
 
Example #12
Source File: JobManagerTest.java    From jobson with Apache License 2.0 5 votes vote down vote up
@Test
public void testSubmitJobEventListenersEchoStdoutWhenExecutorEchoesStdout() throws InterruptedException {
    final Subject<byte[]> stdoutSubject = ReplaySubject.create();
    final byte[] expectedStdoutBytes = generateRandomBytes();
    stdoutSubject.onNext(expectedStdoutBytes);

    final JobExecutor jobExecutor = MockJobExecutor.thatUses(stdoutSubject, Observable.never());
    final JobManager jobManager = createManagerWith(jobExecutor);

    final Semaphore s = new Semaphore(1);
    s.acquire();

    final JobEventListeners listeners = JobEventListeners.createStdoutListener(new Observer<byte[]>() {
        @Override
        public void onSubscribe(@NonNull Disposable disposable) {}

        @Override
        public void onNext(@NonNull byte[] bytes) {
            assertThat(bytes).isEqualTo(expectedStdoutBytes);
            s.release();
        }

        @Override
        public void onError(@NonNull Throwable throwable) {
            fail("Error from observable");
            s.release();
       }

        @Override
        public void onComplete() {}
    });

    jobManager.submit(STANDARD_VALID_REQUEST, listeners);

    if (!s.tryAcquire(1, SECONDS)) {
        fail("Timed out before any bytes received");
    }
}
 
Example #13
Source File: JobExecutorTest.java    From jobson with Apache License 2.0 5 votes vote down vote up
@Test
public void testExecuteEvaluatesToFileAsExpected() throws InterruptedException, IOException {
    final JobExecutor jobExecutor = getInstance();
    final PersistedJob req =
            standardRequestWithCommand("echo", "${toFile(toJSON(inputs))}");
    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();
    final Path p = Paths.get(stringFromStdout);

    assertThat(p.toFile().exists());

    final String loadedJson = new String(Files.readAllBytes(p));

    TestHelpers.assertJSONEqual(loadedJson, toJSON(STANDARD_REQUEST.getInputs()));
}
 
Example #14
Source File: JobManagerTest.java    From jobson with Apache License 2.0 5 votes vote down vote up
@Test
public void testSubmitJobEventListenersEchoStderrWhenExecutorEchoesStderr() throws InterruptedException {
    final Subject<byte[]> stderr = ReplaySubject.create();
    final byte[] stderrBytes = generateRandomBytes();
    stderr.onNext(stderrBytes);

    final JobExecutor jobExecutor = MockJobExecutor.thatUses(Observable.never(), stderr);
    final JobManager jobManager = createManagerWith(jobExecutor);

    final Semaphore s = new Semaphore(1);
    s.acquire();

    final JobEventListeners listeners = JobEventListeners.createStderrListener(new Observer<byte[]>() {
        @Override
        public void onSubscribe(@NonNull Disposable disposable) {}

        @Override
        public void onNext(@NonNull byte[] bytes) {
            assertThat(bytes).isEqualTo(stderrBytes);
            s.release();
        }

        @Override
        public void onError(@NonNull Throwable throwable) {
            fail("Error from observable");
            s.release();
        }

        @Override
        public void onComplete() {}
    });

    jobManager.submit(STANDARD_VALID_REQUEST, listeners);

    if (!s.tryAcquire(1, SECONDS)) {
        fail("Timed out before any bytes received");
    }
}
 
Example #15
Source File: RxBusOlder.java    From SweetMusicPlayer with Apache License 2.0 5 votes vote down vote up
public void unregister(@NonNull Object tag, @NonNull Observable observable) {
    List<Subject> subjects = mSubjectsMapper.get(tag);
    if (subjects != null) {
        subjects.remove(observable);
        if (subjects.isEmpty()) {
            mSubjectsMapper.remove(tag);
        }
        if (DEBUG) {
            Timber.d("[unregister] mSubjectsMapper: " + mSubjectsMapper);
        }
    }
}
 
Example #16
Source File: JobsDAOTest.java    From jobson with Apache License 2.0 5 votes vote down vote up
@Test
public void testPersistStderrReadsDataFromObservable() {
    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;
    });

    dao.appendStderr(jobId, stderrObs);

    assertThat(stderrObsWasRead.get());
}
 
Example #17
Source File: JobsDAOTest.java    From jobson with Apache License 2.0 5 votes vote down vote up
@Test
public void testPersistStdoutReadsDataFromObservable() {
    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;
    });

    dao.appendStdout(jobId, stdoutObs);

    assertThat(stdoutObsWasRead.get());
}
 
Example #18
Source File: JobManager.java    From jobson with Apache License 2.0 5 votes vote down vote up
private void advanceJobQueue() {
    final QueuedJob queuedJob = jobQueue.poll();

    if (queuedJob == null) return;

    final Subject<byte[]> stdout = PublishSubject.create();
    final Subject<byte[]> stderr = PublishSubject.create();

    jobDAO.appendStdout(queuedJob.getId(), stdout);
    jobDAO.appendStderr(queuedJob.getId(), stderr);

    stdout.subscribe(queuedJob.getQueuedListeners().getOnStdoutListener());
    stderr.subscribe(queuedJob.getQueuedListeners().getOnStderrListener());

    try {
        final CancelablePromise<JobExecutionResult> executionPromise =
                jobExecutor.execute(queuedJob, JobEventListeners.create(stdout, stderr));

        final ExecutingJob executingJob =
                ExecutingJob.fromQueuedJob(queuedJob, now(), stdout, stderr);

        executingJobs.put(executingJob.getId(), executingJob);

        updateJobStatus(queuedJob.getId(), RUNNING, "Submitted to executor");

        executionPromise.thenAccept(res -> {
            onExecutionFinished(executingJob, res);
        });

        executingJob.getCompletionPromise().onCancel(() -> {
            executionPromise.cancel(true);
        });
    } catch (Throwable ex) {
        log.error("Error starting job execution: " + ex.toString());
        updateJobStatus(queuedJob.getId(), FATAL_ERROR, "Error executing job: " + ex.toString());
    }
}
 
Example #19
Source File: WsClientAioHander.java    From t-io with Apache License 2.0 5 votes vote down vote up
@Override
public void handler(Packet packet, ChannelContext ctx) throws Exception {
  if (packet instanceof WsPacket) {
    WsPacket wsPacket = (WsPacket) packet;
    if (!wsPacket.isWsEof()) {
      return;
    }
  }
  Subject<Packet> packetPublisher =
      (Subject<Packet>) ctx.getAttribute(WebSocketImpl.packetPublisherKey);
  packetPublisher.onNext(packet);
}
 
Example #20
Source File: RxBus.java    From Toutiao with Apache License 2.0 5 votes vote down vote up
public void unregister(@NonNull Object tag, @NonNull Observable observable) {
    List<Subject> subjects = subjectMapper.get(tag);
    if (null != subjects) {
        subjects.remove(observable);
        if (subjects.isEmpty()) {
            subjectMapper.remove(tag);
            //System.out.println("从rxbus取消注册");
        }
    }
}
 
Example #21
Source File: RxBus.java    From Toutiao with Apache License 2.0 5 votes vote down vote up
public void post(@NonNull Object tag, @NonNull Object content) {
    List<Subject> subjects = subjectMapper.get(tag);
    if (!subjects.isEmpty()) {
        for (Subject subject : subjects) {
            subject.onNext(content);
        }
    }
}
 
Example #22
Source File: Network.java    From AndroidGodEye with Apache License 2.0 4 votes vote down vote up
@Override
protected Subject<NetworkInfo> createSubject() {
    return ReplaySubject.create();
}
 
Example #23
Source File: ThreadDump.java    From AndroidGodEye with Apache License 2.0 4 votes vote down vote up
@Override
protected Subject<List<ThreadInfo>> createSubject() {
    return BehaviorSubject.create();
}
 
Example #24
Source File: Cpu.java    From AndroidGodEye with Apache License 2.0 4 votes vote down vote up
@Override
protected Subject<CpuInfo> createSubject() {
    return BehaviorSubject.create();
}
 
Example #25
Source File: Startup.java    From AndroidGodEye with Apache License 2.0 4 votes vote down vote up
@Override
protected Subject<StartupInfo> createSubject() {
    return BehaviorSubject.create();
}
 
Example #26
Source File: ImageCanary.java    From AndroidGodEye with Apache License 2.0 4 votes vote down vote up
@Override
protected Subject<ImageIssue> createSubject() {
    return ReplaySubject.create();
}
 
Example #27
Source File: Battery.java    From AndroidGodEye with Apache License 2.0 4 votes vote down vote up
@Override
protected Subject<BatteryInfo> createSubject() {
    return BehaviorSubject.create();
}
 
Example #28
Source File: LeakDetector.java    From AndroidGodEye with Apache License 2.0 4 votes vote down vote up
@Override
protected Subject<LeakQueue.LeakMemoryInfo> createSubject() {
    return ReplaySubject.create();
}
 
Example #29
Source File: Crash.java    From AndroidGodEye with Apache License 2.0 4 votes vote down vote up
@Override
protected Subject<List<CrashInfo>> createSubject() {
    return ReplaySubject.create();
}
 
Example #30
Source File: BaseFragment.java    From MVPArms with Apache License 2.0 4 votes vote down vote up
@NonNull
@Override
public final Subject<FragmentEvent> provideLifecycleSubject() {
    return mLifecycleSubject;
}