Search in sources :

Example 1 with Quote

use of com.example.mortar.model.quotes.Quote in project simple-stack by Zhuinden.

the class Chat method getMessages.

public Observable<Message> getMessages() {
    return Observable.create(new ObservableOnSubscribe<Message>() {

        @Override
        public void subscribe(@NonNull ObservableEmitter<Message> emitter) throws Exception {
            final Random random = new Random();
            while (true) {
                if (random.nextInt(PROBABILITY) == 0) {
                    try {
                        User from = users.get(random.nextInt(users.size()));
                        Response<Quotes> response = chats.service.getQuote().execute();
                        Quotes quotes = response.body();
                        if (quotes == null) {
                            throw new Exception("Could not download quotes [" + response.errorBody().string() + "] ");
                        }
                        Quote quote = quotes.getContents().getQuotes().get(0);
                        Message next = new Message(from, quote.getQuote());
                        messages.add(next);
                        if (!emitter.isDisposed()) {
                            emitter.onNext(next);
                        }
                    } catch (Exception e) {
                        if (!emitter.isDisposed()) {
                            emitter.onError(e);
                            break;
                        }
                    }
                }
                try {
                    // Hijacking the thread like this is sleazey, but you get the idea.
                    Thread.sleep(SLEEP_MILLIS);
                } catch (InterruptedException e) {
                    if (!emitter.isDisposed()) {
                        emitter.onError(e);
                    }
                    break;
                }
            }
        }
    }).startWith(//
    messages).subscribeOn(//
    Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
}
Also used : Quote(com.example.mortar.model.quotes.Quote) ObservableOnSubscribe(io.reactivex.ObservableOnSubscribe) Random(java.util.Random) NonNull(io.reactivex.annotations.NonNull) Quotes(com.example.mortar.model.quotes.Quotes) ObservableEmitter(io.reactivex.ObservableEmitter)

Aggregations

Quote (com.example.mortar.model.quotes.Quote)1 Quotes (com.example.mortar.model.quotes.Quotes)1 ObservableEmitter (io.reactivex.ObservableEmitter)1 ObservableOnSubscribe (io.reactivex.ObservableOnSubscribe)1 NonNull (io.reactivex.annotations.NonNull)1 Random (java.util.Random)1