在RxJava链中设置变量

时间:2016-12-07 09:27:48

标签: android rx-java rx-android

我正在使用ReactiveLocation library。基本上,我希望在4秒内获得足够精确的位置。如果在那段时间内没有收到足够精确的位置,但其他位置则返回最高精度位置。

只要收到足够准确的位置,就会返回并完成观察。

我会发布我正在尝试的代码。我可能,也可能是,以错误的方式解决这个问题。

LocationRequest request = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setFastestInterval(FASTEST_UPDATE_INTERVAL)
            .setSmallestDisplacement(MIN_DISTANCE_UPDATE_INTERVAL);

    if ( expirationSeconds != null )
        request.setExpirationDuration(TimeUnit.SECONDS.toMillis(expirationSeconds));

    ReactiveLocationProvider locationProvider = new ReactiveLocationProvider(context);
    Observable<Location> observable = locationProvider.getUpdatedLocation(request)
                .doOnNext(new Action1<Location>() {
                    @Override
                    public void call(Location location) {
                        if ( mostAccurateLocation == null )
                            mostAccurateLocation = location;

                        if ( location.getAccuracy() < mostAccurateLocation.getAccuracy() )
                            mostAccurateLocation = location;
                    }
                })
                .filter(new Func1<Location, Boolean>() {
                    @Override
                    public Boolean call(Location location) {
                        return location.getAccuracy() < sufficientAccuracy ;
                    }
                });

    if ( expirationSeconds != null )
        observable = observable.timeout( expirationSeconds, TimeUnit.SECONDS, Observable.just(mostAccurateLocation), backgroundThread );

    return observable.firstOrDefault(mostAccurateLocation)
                     .doOnNext(new Action1<Location>() {
                        @Override
                        public void call(Location location) {
                            lastLocation = location;
                        }
                    });

1 个答案:

答案 0 :(得分:0)

好的,我发现了问题。超时正在进行,但显然,超时启动的可观察性是使用mostAccurateLocation变量,就像在可观察的创建时一样。

为了解决这个问题,我使用了Observable.defer模式,因此它只会在订阅时创建Observable<Location>

    if ( expirationSeconds != null ) {
        Observable<Location> mostAccurateLocationObservable = Observable.defer(new Func0<Observable<Location>>() {
            @Override
            public Observable<Location> call() {
                return Observable.just(mostAccurateLocation);
            }
        });

        observable = observable.timeout( expirationSeconds, TimeUnit.SECONDS, mostAccurateLocationObservable, backgroundThread );
    }