All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.nytimes.android.external.fs.FSReader Maven / Gradle / Ivy

package com.nytimes.android.external.fs;

import com.nytimes.android.external.fs.filesystem.FileSystem;
import com.nytimes.android.external.store.base.DiskRead;

import java.io.FileNotFoundException;

import javax.annotation.Nonnull;

import okio.BufferedSource;
import rx.Emitter;
import rx.Observable;
import rx.functions.Action1;

/**
 * FSReader is used when persisting from file system
 * PathResolver will be used in creating file system paths based on cache keys.
 * Make sure to have keys containing same data resolve to same "path"
 *
 * @param  key type
 */
public class FSReader implements DiskRead {
    final FileSystem fileSystem;
    final PathResolver pathResolver;

    public FSReader(FileSystem fileSystem, PathResolver pathResolver) {
        this.fileSystem = fileSystem;
        this.pathResolver = pathResolver;
    }

    @Nonnull
    @Override
    public Observable read(@Nonnull final T key) {
        return Observable.fromEmitter(new Action1>() {
            @Override
            public void call(Emitter emitter) {
                String resolvedKey = pathResolver.resolve(key);
                boolean exists = fileSystem.exists(resolvedKey);
              
                if (exists) {
                    try {
                        BufferedSource bufferedSource = fileSystem.read(resolvedKey);
                        emitter.onNext(bufferedSource);
                        emitter.onCompleted();
                    } catch (FileNotFoundException e) {
                        emitter.onError(e);
                    }
                } else {
                    emitter.onCompleted();
                }
            }
        }, Emitter.BackpressureMode.NONE);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy