Java Code Examples for io.reactivex.Observable.subscribe()

The following are Jave code examples for showing how to use subscribe() of the io.reactivex.Observable class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: android-rxmvp-sandbox   File: RxJava.java   View Source Code Vote up 6 votes
/**
   * For example, if one needs a signaller-like source,
   * a shared enum can be defined and its solo instance onNext'd:
   */
  @Test
  public void SignallerExample() {
    Observable<Object> source = Observable.create((ObservableEmitter<Object> emitter) -> {
      System.out.println("Side-effect 1");
      emitter.onNext(Irrelevant.INSTANCE);

      System.out.println("Side-effect 2");
      emitter.onNext(Irrelevant.INSTANCE);

      System.out.println("Side-effect 3");
//            emitter.onNext(Irrelevant.INSTANCE);
    });

    source.subscribe(e -> { /* Ignored. */ }, Throwable::printStackTrace);
  }
 
Example 2
Project: Reactive-Programming-With-Java-9   File: Modern_Testing.java   View Source Code Vote up 6 votes
@Test
public void test_just_new() {
	Observable<Integer> observable = Observable.just(12, 34, 6);
	TestObserver<Integer> testObserver = new TestObserver<>();

	observable.subscribe(testObserver);

	List<Integer> list = new ArrayList();
	testObserver.assertComplete();
	testObserver.assertResult(12, 34, 6);
	testObserver.assertValueCount(3);
	testObserver.assertNoErrors();
	testObserver.assertValueAt(2, (value) -> {
		// TODO Auto-generated method stub
		return value == 34;
	});

}
 
Example 3
Project: jobson   File: FilesystemJobsDAO.java   View Source Code Vote up 6 votes
private Disposable persistObservableToJobFile(JobId jobId, String jobFilename, Observable<byte[]> o) {
    if (!resolveJobDir(jobId).isPresent())
        throw new RuntimeException(jobId + ": cannot persist stdout: job dir does not exist");

    final Path stdoutPath = resolveJobDir(jobId).get().resolve(jobFilename);

    final AtomicReference<FileOutputStream> outputStream =
            new AtomicReference<>(null);
    return o.subscribe(
            bytes -> {
                if (outputStream.get() == null)
                    outputStream.set(new FileOutputStream(stdoutPath.toFile()));
                outputStream.get().write(bytes);
            },
            error -> {
                if (outputStream.get() != null)
                    outputStream.get().close();
            },
            () -> {
                if (outputStream.get() != null)
                    outputStream.get().close();
            });
}
 
Example 4
Project: Learning-RxJava   File: Ch2_2.java   View Source Code Vote up 6 votes
public static void main(String[] args) {
    Observable<String> source = Observable.create(emitter -> {
        try {
            emitter.onNext("Alpha");
            emitter.onNext("Beta");
            emitter.onNext("Gamma");
            emitter.onNext("Delta");
            emitter.onNext("Epsilon");
            emitter.onComplete();
        } catch (Throwable e) {
            emitter.onError(e);
        }
    });
    source.subscribe(s -> System.out.println("RECEIVED: " + s),
            Throwable::printStackTrace);
}
 
Example 5
Project: RxJava4AndroidDemos   File: Create.java   View Source Code Vote up 6 votes
@Override
public void test3() {
    Log.i(TAG, "test3() Create simple demo, onNext() twice");
    Observable<String> observable = Observable.create(new ObservableOnSubscribe<String>() {
        @Override
        public void subscribe(@NonNull ObservableEmitter<String> e) throws Exception {
            for (int i = 0; i < 3; i++) {
                e.onNext(String.valueOf(i));
            }
        }
    });
    for (int time = 0; time < 2; time++) {
        observable.subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                Log.d(TAG, "Consumer<String> accept() s: " + s);
            }
        });
    }
}
 
Example 6
Project: sqlbrite-sqlcipher   File: BriteDatabaseTest.java   View Source Code Vote up 5 votes
@Test public void querySubscribedToDuringTransactionThrows() {
  Observable<Query> query = db.createQuery(TABLE_EMPLOYEE, SELECT_EMPLOYEES);

  db.newTransaction();
  query.subscribe(o);
  o.assertErrorContains("Cannot subscribe to observable query in a transaction.");
}
 
Example 7
Project: oracle-javamag-vertx-rxjava   File: RxCreateObservable.java   View Source Code Vote up 5 votes
public static void main(String[] args) {

    List<String> data = Arrays.asList("foo", "bar", "baz");
    Random random = new Random();
    Observable<String> source = Observable.create(subscriber -> {
      for (String s : data) {
        if (random.nextInt(6) == 0) {
          subscriber.onError(new RuntimeException("Bad luck for you..."));
        }
        subscriber.onNext(s);
      }
      subscriber.onComplete();
    });

    for (int i = 0; i < 10; i++) {
      logger.info("=======================================");
      source.subscribe(next -> logger.info("Next: {}", next),
        error -> logger.error("Whoops"),
        () -> logger.info("Done"));
    }

    logger.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
    source
      .retry(5)
      .subscribe(next -> logger.info("Next: {}", next),
        error -> logger.error("Whoops"),
        () -> logger.info("Done"));
  }
 
Example 8
Project: Reactive-Programming-With-Java-9   File: DemoTimer.java   View Source Code Vote up 5 votes
public static void main(String[] args) {
	// TODO Auto-generated method stub
	Observable<Long> observable=Observable.timer(1,TimeUnit.SECONDS,Schedulers.computation()).flatMap(i->Observable.just(12l,13l,300l,400l));
	observable.subscribe(new Observer<Long>() {

		@Override
		public void onComplete() {
			// TODO Auto-generated method stub00
			System.out.println("completed");
			
		}

		@Override
		public void onError(Throwable throwable) {
			// TODO Auto-generated method stub
			throwable.printStackTrace();
		}

		@Override
		public void onNext(Long value) {
			// TODO Auto-generated method stub
			System.out.println(value);
			
		}

		@Override
		public void onSubscribe(Disposable arg0) {
			// TODO Auto-generated method stub
			System.out.println("subscribe");
			
		}
	});

	try {
		Thread.sleep(80000);
	} catch (InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example 9
Project: RosterManager   File: ItemListActivityTest.java   View Source Code Vote up 5 votes
@Test
public void shouldGetPreviousShifts() throws Exception {
    shiftService.startAShift(shift);
    shiftService.endAShift(shift);

    Observable<List<FinishedShift>> observable = shiftService.getPreviousShifts();
    TestObserver<List<FinishedShift>> testObserver = new TestObserver<>();
    observable.subscribe(testObserver);
    testObserver.assertNoErrors();
}
 
Example 10
Project: sqlbrite-sqlcipher   File: BriteDatabaseTest.java   View Source Code Vote up 5 votes
@Test public void queryOnlyNotifiedAfterSubscribe() {
  Observable<Query> query = db.createQuery(TABLE_EMPLOYEE, SELECT_EMPLOYEES);
  o.assertNoMoreEvents();

  db.insert(TABLE_EMPLOYEE, employee("john", "John Johnson"));
  o.assertNoMoreEvents();

  query.subscribe(o);
  o.assertCursor()
      .hasRow("alice", "Alice Allison")
      .hasRow("bob", "Bob Bobberson")
      .hasRow("eve", "Eve Evenson")
      .hasRow("john", "John Johnson")
      .isExhausted();
}
 
Example 11
Project: code-examples-android-expert   File: RxJavaUnitTest.java   View Source Code Vote up 5 votes
@Test
public void returnAValue(){
    result = "";
    Observable<String> observer = Observable.just("Hello"); // provides datea
    observer.subscribe(s -> result=s); // Callable as subscriber
    assertTrue(result.equals("Hello"));
}
 
Example 12
Project: Learning-RxJava   File: Ch5_17.java   View Source Code Vote up 5 votes
public static void main(String[] args) {
        Observable<String> source =
                Observable.just("Alpha", "Beta", "Gamma",
                        "Delta", "Epsilon")
                        .replay(1)
                        .autoConnect();
//Observer 1
        source.subscribe(l -> System.out.println("Observer 1: " +
                l));
//Observer 2
        source.subscribe(l -> System.out.println("Observer 2: " +
                l));
    }
 
Example 13
Project: Reactive-Programming-With-Java-9   File: MyObserver.java   View Source Code Vote up 5 votes
public static void main(String[] args) {
	// TODO Auto-generated method stub
	
	Observable<Long>observable=Observable.rangeLong(1l,3l);
	Observer< Long> observer=new Observer<Long>() {

		@Override
		public void onComplete() {
			// TODO Auto-generated method stub
			System.out.println("on complete");
			
		}

		@Override
		public void onError(Throwable throwable) {
			// TODO Auto-generated method stub
			throwable.printStackTrace();
			
		}

		@Override
		public void onNext(Long value) {
			// TODO Auto-generated method stub
			System.out.println(""+value);
			
		}

		@Override
		public void onSubscribe(Disposable disposable) {
			// TODO Auto-generated method stub
			System.out.println(disposable.isDisposed());
			disposable.dispose();
			
		}
	};
	observable.subscribe(observer);
	
}
 
Example 14
Project: Reactive-Programming-With-Java-9   File: Traditional_Testing.java   View Source Code Vote up 5 votes
@Test
public void test_just() {
	Observable<Integer> observable = Observable.just(12, 34, 6);
	ArrayList<Integer> list = new ArrayList();
	observable.subscribe(item -> list.add(item));

	assertNotNull(list);
	assertEquals(3, list.size());
	assertEquals(6, list.get(2).intValue());
}
 
Example 15
Project: RxJava4AndroidDemos   File: Create.java   View Source Code Vote up 5 votes
@Override
public void test4() {
    Log.i(TAG, "test4() Create simple demo, onNext() and onComplete() twice");
    Observable<String> observable = Observable.create(new ObservableOnSubscribe<String>() {
        @Override
        public void subscribe(@NonNull ObservableEmitter<String> e) throws Exception {
            for (int i = 0; i < 3; i++) {
                e.onNext(String.valueOf(i));
            }
            e.onComplete();
        }
    });
    for (int time = 0; time < 2; time++) {
        observable.subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                Log.d(TAG, "Consumer<String> accept() s: " + s);
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                Log.d(TAG, "Consumer<Throwable> accept() throwable: " + throwable);
            }
        }, new Action() {
            @Override
            public void run() throws Exception {
                Log.d(TAG, "Action run() for onComplete()");
            }
        });
    }
}
 
Example 16
Project: Reactive-Programming-With-Java-9   File: DemoObservable_never.java   View Source Code Vote up 4 votes
public static void main(String[] args) {
	// TODO Auto-generated method stub
	Observable<String> observable=Observable.never();
	observable.subscribe(item-> System.out.println("we got"+item));
}
 
Example 17
Project: reactive-playing   File: Samples.java   View Source Code Vote up 4 votes
private static void printOn(Observable<?> observable) {
    observable.subscribe(System.out::println);
}
 
Example 18
Project: java-rxjava   File: TracingObserverTest.java   View Source Code Vote up 3 votes
private void executeParallelObservable(final String name, List<Integer> result) {
  Observable<Integer> observable = createParallelObservable(mockTracer);

  Observer<Integer> observer = observer(name, result);

  observable.subscribe(new TracingObserver<>(observer, "parallel", mockTracer));
}
 
Example 19
Project: code-examples-android-expert   File: lessonA_CreatingObservableStreams.java   View Source Code Vote up 3 votes
/**
 * An observable stream calls 3 major lifecycle methods as it does it's
 * work: onNext(), onCompleted(), and onError().
 * <p>
 * onNext(): An Observable calls this method whenever the Observable emits
 * an item. This method takes as a parameter the item emitted by the
 * Observable.
 * <p>
 * onError(): An Observable calls this method to indicate that it has failed
 * to generate the expected data or has encountered some other error. This
 * stops the Observable and it will not make further calls to onNext or
 * onCompleted. The onError method takes as its parameter an indication of
 * what caused the error.
 * <p>
 * onComplete(): An Observable calls this method after it has called onNext
 * for the final time, if it has not encountered any errors.
 */
@Test
public void _anObservableStreamShouldEmitsThreeMajorEventTypes() {
	Observable<Integer> pipelineOfData = Observable.just(1, 2, 3, 4, 5);
	pipelineOfData.doOnNext(integer -> mCount1++).doOnComplete(() -> mCount2++).doOnError(throwable -> mCount3++)
			.subscribe(testObserver);
	pipelineOfData.subscribe(integer -> System.out.println(integer));
	testObserver.awaitTerminalEvent();
	assertThat(mCount1).isEqualTo(____);
	assertThat(mCount2).isEqualTo(____);
	assertThat(mCount3).isEqualTo(____);
}
 
Example 20
Project: RxRedux   File: BaseViewModel.java   View Source Code Vote up 2 votes
/**
 * Pass in the stream of events to start the dialog.
 *
 * @param events {@link Observable} stream of user events.
 */
public void processEvents(Observable<BaseEvent> events) {
    events.subscribe(eventsSubject);
}