Java Code Examples for rx.subjects.ReplaySubject#create()

The following examples show how to use rx.subjects.ReplaySubject#create() . 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: CoordinatedWeatherManager.java    From rain-or-shine with Apache License 2.0 6 votes vote down vote up
private Observable<List<String>> getCityNames() {
    if (cityNames == null) {
        cityNames = ReplaySubject.create(1);

        geoNamesClient.getCities()
                .flatMap(cities -> Observable.from(cities.geonames))
                .map(city -> {
                    String format = String.format("%s,%s", city.name, city.countrycode);
                    return format;
                })
                .toList()
                .subscribe(cityNames);
    }
    Log.d(TAG, "Returning city names");
    return cityNames.asObservable();
}
 
Example 2
Source File: ObservableQueue.java    From Jockey with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an Observable stream from this queue. There should only ever be one subscriber to
 * this method. Calling this method twice will complete any previously opened observable
 * (leaving unprocessed elements in the queue).
 * @return An observable containing the contents of the queue in order
 */
public Observable<T> toObservable() {
    synchronized (mLock) {
        if (mSubject != null) {
            mSubject.onCompleted();
        }

        if (mQueue.isEmpty()) {
            mSubject = ReplaySubject.create();
        } else {
            mSubject = ReplaySubject.create(mQueue.size());

            for (T data : mQueue) {
                mSubject.onNext(data);
            }
        }
    }

    return mSubject.map(item -> {
        mQueue.remove();
        return item;
    }).asObservable();
}
 
Example 3
Source File: AppGoogleAds.java    From fyber_mobile_offers with MIT License 6 votes vote down vote up
@Override
public Observable<Boolean> getAdIdEnabledObservable() {
    // Observable that emits Google Tracking Enabled
    if (adIdEnabledSubscription == null || adIdEnabledSubscription.isUnsubscribed()) {
        adIdEnabledSubject = ReplaySubject.create();

        adIdEnabledSubscription = Observable
                .concat(getAdIdEnabledFromMemoryObservable(),
                        getAdIdEnabledFromGoogleObservable())
                .first(entity -> entity != null)
                // lets retry if something goes wrong!
                .retry(2)
                .subscribe(adIdEnabledSubject);
    }

    return adIdEnabledSubject.asObservable();
}
 
Example 4
Source File: AppGoogleAds.java    From fyber_mobile_offers with MIT License 6 votes vote down vote up
@Override
public Observable<String> getAdIdObservable() {
    // Observable that emits Google Advertising adIdSubscription
    if (adIdSubscription == null || adIdSubscription.isUnsubscribed()) {
        adIdSubject = ReplaySubject.create();

        adIdSubscription = Observable
                .concat(getAdIdFromMemoryObservable(),
                        getAdIdFromGoogleObservable())
                .first(entity -> entity != null)
                // lets retry if something goes wrong!
                .retry(2)
                .subscribe(adIdSubject);
    }

    return adIdSubject.asObservable();
}
 
Example 5
Source File: BizkeeperHandlerDelegate.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
protected HystrixObservable<Response> forceFallbackCommand(Invocation invocation) {
  return new HystrixObservable<Response>() {
    @Override
    public Observable<Response> observe() {
      ReplaySubject<Response> subject = ReplaySubject.create();
      final Subscription sourceSubscription = toObservable().subscribe(subject);
      return subject.doOnUnsubscribe(sourceSubscription::unsubscribe);
    }

    @Override
    public Observable<Response> toObservable() {
      return Observable.create(f -> {
        try {
          f.onNext(FallbackPolicyManager.getFallbackResponse(handler.groupname, null, invocation));
        } catch (Exception e) {
          f.onError(e);
        }
      });
    }
  };
}
 
Example 6
Source File: IngressPolicies.java    From mantis with Apache License 2.0 5 votes vote down vote up
public static IngressPolicy allowOnlyLocalhost() {
    ReplaySubject<Set<String>> subject = ReplaySubject.create();
    Set<String> list = new HashSet<String>();
    list.add("127.0.0.1");
    subject.onNext(list);
    return new InetAddressWhiteListIngressPolicy(subject);
}
 
Example 7
Source File: DynamicConnectionSetTest.java    From mantis with Apache License 2.0 5 votes vote down vote up
@Test
public void testMergeInWithDeltaEndpointService() {
    PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000);
    final int server1Port = portSelector.acquirePort();
    final int server2Port = portSelector.acquirePort();

    // setup servers
    RemoteRxServer server1 = RemoteObservable.serve(server1Port, Observable.range(1, 50), Codecs.integer());
    RemoteRxServer server2 = RemoteObservable.serve(server2Port, Observable.range(51, 50), Codecs.integer());

    server1.start();
    server2.start();

    ReplaySubject<List<Endpoint>> subject = ReplaySubject.create();
    List<Endpoint> endpoints = new LinkedList<Endpoint>();
    endpoints.add(new Endpoint("localhost", server1Port));
    endpoints.add(new Endpoint("localhost", server2Port));
    subject.onNext(endpoints);
    subject.onCompleted();

    DynamicConnectionSet<Integer> cm
            = DynamicConnectionSet.create(new ConnectToObservable.Builder<Integer>()
            .decoder(Codecs.integer()));
    cm.setEndpointInjector(new ToDeltaEndpointInjector(subject));

    int sum = MathObservable.sumInteger(Observable.merge(cm.observables()))
            .toBlocking()
            .last();
    Assert.assertEquals(5050, sum);

}
 
Example 8
Source File: HttpMetaRequest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Override
public Observable<RibbonResponse<Observable<T>>> observe() {
    HystrixObservableCommandChain<T> commandChain = request.createHystrixCommandChain();
    Observable<ResultCommandPair<T>> notificationObservable = commandChain.toResultCommandPairObservable();
    notificationObservable = retainBufferIfNeeded(notificationObservable);
    ReplaySubject<ResultCommandPair<T>> subject = ReplaySubject.create();
    notificationObservable.subscribe(subject);
    return convertToRibbonResponse(commandChain, subject);
}
 
Example 9
Source File: RemoteObservableTest.java    From mantis with Apache License 2.0 5 votes vote down vote up
@Test
public void testServedMergedObservables() {
    // setup
    Observable<Integer> os1 = Observable.range(0, 101);
    Observable<Integer> os2 = Observable.range(100, 101);
    ReplaySubject<Observable<Integer>> subject = ReplaySubject.create();
    subject.onNext(os1);
    subject.onNext(os2);
    subject.onCompleted();

    PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000);
    int port = portSelector.acquirePort();

    RemoteRxServer server = new RemoteRxServer.Builder()
            .port(port)
            .addObservable(new ServeObservable.Builder<Integer>()
                    .encoder(Codecs.integer())
                    .observable(Observable.merge(subject))
                    .build())
            .build();

    // serve
    server.start();

    // connect
    Observable<Integer> oc = RemoteObservable.connect("localhost", port, Codecs.integer());
    // assert
    MathObservable.sumInteger(oc).toBlocking().forEach(new Action1<Integer>() {
        @Override
        public void call(Integer t1) {
            Assert.assertEquals(20200, t1.intValue()); // sum of number 0-200
        }
    });
}
 
Example 10
Source File: RemoteObservableTest.java    From mantis with Apache License 2.0 4 votes vote down vote up
@Test
public void testServedMergedObservablesAddAfterConnect() {
    // setup
    Observable<Integer> os1 = Observable.range(0, 100);
    Observable<Integer> os2 = Observable.range(100, 100);
    ReplaySubject<Observable<Integer>> subject = ReplaySubject.create();
    subject.onNext(os1);
    subject.onNext(os2);
    // serve
    PortSelectorWithinRange portSelector = new PortSelectorWithinRange(8000, 9000);
    int serverPort = portSelector.acquirePort();

    RemoteRxServer server = new RemoteRxServer.Builder()
            .port(serverPort)
            .addObservable(new ServeObservable.Builder<Integer>()
                    .encoder(Codecs.integer())
                    .observable(Observable.merge(subject))
                    .build())
            .build();
    server.start();

    // add after serve
    Observable<Integer> os3 = Observable.range(200, 100);
    subject.onNext(os3);

    // connect
    Observable<Integer> oc = RemoteObservable.connect("localhost", serverPort, Codecs.integer());

    // add after connect
    Observable<Integer> os4 = Observable.range(300, 101);
    subject.onNext(os4);
    subject.onCompleted();

    // assert
    MathObservable.sumInteger(oc).toBlocking().forEach(new Action1<Integer>() {
        @Override
        public void call(Integer t1) {
            Assert.assertEquals(80200, t1.intValue()); // sum of number 0-200
        }
    });
}
 
Example 11
Source File: JobScenarioBuilder.java    From titus-control-plane with Apache License 2.0 4 votes vote down vote up
private TaskHolder() {
    this.taskEventStream = ReplaySubject.create();
    this.taskScenarioBuilder = new TaskScenarioBuilder(titusOperations, JobScenarioBuilder.this, taskEventStream,
            schedulingService, diagnosticReporter);
}
 
Example 12
Source File: RxJava1Proxies.java    From RHub with Apache License 2.0 4 votes vote down vote up
public static RxJava1SubjProxy replaySubjectProxy() {
    return new RxJava1SubjProxy(ReplaySubject.create());
}
 
Example 13
Source File: OffersInteractorImpl.java    From fyber_mobile_offers with MIT License 4 votes vote down vote up
@Override
public Observable<OfferResponse> loadOffers(int page,
                                            String format,
                                            int applicationId,
                                            String userId,
                                            String locale,
                                            String osVersion,
                                            long timestamp,
                                            String googleAdId,
                                            boolean googleAdIdLimitedTrackingEnabled,
                                            String ip,
                                            String pub0,
                                            int offerTypes,
                                            String device,
                                            String apiKey) {
    if (offersSubscription == null || offersSubscription.isUnsubscribed()) {
        offersSubject = ReplaySubject.create();

        String hashKey = new HashGenerator()
                .addParam(FyberApi.PAGE, page)
                .addParam(FyberApi.FORMAT, Constants.FORMAT_JSON)
                .addParam(FyberApi.APP_ID, applicationId)
                .addParam(FyberApi.USER_ID, userId)
                .addParam(FyberApi.LOCALE, locale)
                .addParam(FyberApi.OS_VERSION, osVersion)
                .addParam(FyberApi.TIMESTAMP, timestamp)
                .addParam(FyberApi.GOOGLE_AD_ID, googleAdId)
                .addParam(FyberApi.GOOGLE_AD_ID_LIMITED_TRACKING_ENABLED, googleAdIdLimitedTrackingEnabled)
                .addParam(FyberApi.IP, ip)
                .addParam(FyberApi.PUB0, pub0)
                .addParam(FyberApi.OFFER_TYPES, Constants.OFFER_TYPES)
                .addParam(FyberApi.DEVICE, device)
                .generate(apiKey);

        offersSubscription = api.getOffers(
                format,
                applicationId,
                userId,
                locale,
                osVersion,
                timestamp,
                hashKey,
                googleAdId,
                googleAdIdLimitedTrackingEnabled,
                ip,
                pub0,
                page,
                offerTypes,
                device)
                .subscribeOn(scheduler.backgroundThread())
                .observeOn(scheduler.mainThread())
                .subscribe(offersSubject);
    }

    return offersSubject.asObservable();
}
 
Example 14
Source File: HttpRequest.java    From ribbon with Apache License 2.0 4 votes vote down vote up
@Override
public Observable<T> observe() {
    ReplaySubject<T> subject = ReplaySubject.create();
    getObservable().subscribe(subject);
    return subject;
}
 
Example 15
Source File: ToDeltaEndpointInjectorTest.java    From mantis with Apache License 2.0 4 votes vote down vote up
@Test
public void deltaTestWithIds() {

    ReplaySubject<List<Endpoint>> subject = ReplaySubject.create();
    ToDeltaEndpointInjector service = new ToDeltaEndpointInjector(subject);

    // 1. add endpoints
    List<Endpoint> endpoints = new LinkedList<Endpoint>();
    endpoints.add(new Endpoint("localhost", 1234, "abc"));
    endpoints.add(new Endpoint("localhost", 2468, "xyz"));
    subject.onNext(endpoints);
    // 2. nothing changes
    endpoints = new LinkedList<Endpoint>();
    endpoints.add(new Endpoint("localhost", 1234, "abc"));
    endpoints.add(new Endpoint("localhost", 2468, "xyz"));
    subject.onNext(endpoints);
    // 3. remove endpoint by leaving out second endpoint
    endpoints = new LinkedList<Endpoint>();
    endpoints.add(new Endpoint("localhost", 1234, "abc"));
    subject.onNext(endpoints);
    // 4. remove all
    endpoints = new LinkedList<Endpoint>();
    subject.onNext(endpoints);
    // 5. add back
    endpoints = new LinkedList<Endpoint>();
    endpoints.add(new Endpoint("localhost", 1234, "abc"));
    endpoints.add(new Endpoint("localhost", 2468, "xyz"));
    subject.onNext(endpoints);
    subject.onCompleted();

    BlockingObservable<EndpointChange> be = service.deltas().toBlocking();

    Iterator<EndpointChange> iter = be.getIterator();
    Assert.assertTrue(iter.hasNext());

    EndpointChange ce2 = iter.next();
    Assert.assertEquals(ce2.getEndpoint().getSlotId(), "xyz");
    Assert.assertEquals(ce2.getType(), EndpointChange.Type.add);

    EndpointChange ce1 = iter.next();
    Assert.assertEquals(ce1.getEndpoint().getSlotId(), "abc");
    Assert.assertEquals(ce1.getType(), EndpointChange.Type.add);


    EndpointChange ce3 = iter.next();
    Assert.assertEquals(ce3.getEndpoint().getSlotId(), "xyz");
    Assert.assertEquals(ce3.getType(), EndpointChange.Type.complete);


    EndpointChange ce4 = iter.next();
    Assert.assertEquals(ce4.getEndpoint().getSlotId(), "abc");
    Assert.assertEquals(ce4.getType(), EndpointChange.Type.complete);

    EndpointChange ce6 = iter.next();
    Assert.assertEquals(ce6.getEndpoint().getSlotId(), "xyz");
    Assert.assertEquals(ce6.getType(), EndpointChange.Type.add);

    EndpointChange ce5 = iter.next();
    Assert.assertEquals(ce5.getEndpoint().getSlotId(), "abc");
    Assert.assertEquals(ce5.getType(), EndpointChange.Type.add);

}
 
Example 16
Source File: ClientToServerChannelHandler.java    From datamill with ISC License 4 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext context, Object message) {
    if (message instanceof HttpRequest) {
        HttpRequest request = (HttpRequest) message;

        if (HttpUtil.is100ContinueExpected(request)) {
            sendContinueResponse(context);
        }

        bodyStream = ReplaySubject.create();
        serverRequest = ServerRequestBuilder.buildServerRequest(request, bodyStream);

        processRequest(context, request);

        if (request.decoderResult().isFailure()) {
            bodyStream.onError(request.decoderResult().cause());
        }
    }

    if (message instanceof HttpContent) {
        HttpContent httpContent = (HttpContent) message;

        ByteBuf content = httpContent.content();
        if (content.isReadable()) {
            bodyStream.onNext(content.nioBuffer());

            if (httpContent.decoderResult().isFailure()) {
                bodyStream.onError(httpContent.decoderResult().cause());
            }
        }

        if (message instanceof LastHttpContent) {
            LastHttpContent trailer = (LastHttpContent) message;
            if (!trailer.trailingHeaders().isEmpty()) {
                serverRequest.setTrailingHeaders(ServerRequestBuilder.buildHeadersMap(trailer.trailingHeaders()));
            }

            bodyStream.onCompleted();
        }
    }
}
 
Example 17
Source File: ToDeltaEndpointInjectorTest.java    From mantis with Apache License 2.0 4 votes vote down vote up
@Test
public void deltaTest() {

    ReplaySubject<List<Endpoint>> subject = ReplaySubject.create();
    ToDeltaEndpointInjector service = new ToDeltaEndpointInjector(subject);

    // 1 add endpoints
    List<Endpoint> endpoints = new LinkedList<Endpoint>();
    endpoints.add(new Endpoint("localhost", 1234));
    endpoints.add(new Endpoint("localhost", 2468));
    subject.onNext(endpoints);
    // 2 remove endpoint by leaving out second endpoint
    endpoints = new LinkedList<Endpoint>();
    endpoints.add(new Endpoint("localhost", 1234));
    subject.onNext(endpoints);
    // 3 remove other
    endpoints = new LinkedList<Endpoint>();
    subject.onNext(endpoints);
    // 4 add back
    endpoints = new LinkedList<Endpoint>();
    endpoints.add(new Endpoint("localhost", 1234));
    endpoints.add(new Endpoint("localhost", 2468));
    subject.onNext(endpoints);
    subject.onCompleted();

    BlockingObservable<EndpointChange> be = service.deltas().toBlocking();

    // check for two adds
    Iterator<EndpointChange> iter = be.getIterator();
    Assert.assertTrue(iter.hasNext());
    EndpointChange ce1 = iter.next();
    Assert.assertEquals(ce1.getEndpoint().getSlotId(), "localhost:1234");
    Assert.assertEquals(ce1.getType(), EndpointChange.Type.add);
    EndpointChange ce2 = iter.next();
    Assert.assertEquals(ce2.getEndpoint().getSlotId(), "localhost:2468");
    Assert.assertEquals(ce2.getType(), EndpointChange.Type.add);

    // check for complete
    EndpointChange ce3 = iter.next();
    Assert.assertEquals(ce3.getEndpoint().getSlotId(), "localhost:2468");
    Assert.assertEquals(ce3.getType(), EndpointChange.Type.complete);

    // check for complete
    EndpointChange ce4 = iter.next();
    Assert.assertEquals(ce4.getEndpoint().getSlotId(), "localhost:1234");
    Assert.assertEquals(ce4.getType(), EndpointChange.Type.complete);

    // check for add
    EndpointChange ce5 = iter.next();
    Assert.assertEquals(ce5.getEndpoint().getSlotId(), "localhost:1234");
    Assert.assertEquals(ce5.getType(), EndpointChange.Type.add);
    EndpointChange ce6 = iter.next();
    Assert.assertEquals(ce6.getEndpoint().getSlotId(), "localhost:2468");
    Assert.assertEquals(ce6.getType(), EndpointChange.Type.add);
}
 
Example 18
Source File: HystrixCommandChainTest.java    From ribbon with Apache License 2.0 4 votes vote down vote up
@Override
protected Observable<String> construct() {
    Subject<String, String> subject = ReplaySubject.create();
    fireEvents(subject);
    return subject;
}
 
Example 19
Source File: StatRequest.java    From couchbase-jvm-core with Apache License 2.0 4 votes vote down vote up
public StatRequest(final String key, final String hostname, final String bucket) {
    super(key, bucket, null, null, ReplaySubject.<CouchbaseResponse>create());
    this.hostname = hostname;
}
 
Example 20
Source File: MergedObservable.java    From mantis with Apache License 2.0 4 votes vote down vote up
public static <T> MergedObservable<T> createWithReplay(int expectedTerminalCount) {
    return new MergedObservable<T>(expectedTerminalCount, ReplaySubject.<Observable<T>>create());
}