使用带有 Cursor 的 RXAndroid 发出数据

Use RXAndroid with Cursor to emit data

我有以下模特

public class VideosOwn {
    public long _id;
    public String _title;
    public String _width;
    public long _height;
    public String _orientation;
    public long _size;

    public VideosOwn(long _id, String _title, String _width, long _height, String _orientation, long _size) {
        this._id = _id;
        this._title = _title;
        this._width = _width;
        this._height = _height;
        this._orientation = _orientation;
        this._size = _size;

    }
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

和以下使用 ContentResolover

将数据作为数组获取的方法
public ArrayList<VideosOwn> GetVideoList(Context mContext) {
        ArrayList<VideosOwn> videos = new ArrayList<>();
        Cursor cursor = mContext.getContentResolver().query(VideosUri,
                VideosProjection, null, null, MediaStore.Video.Media.DATE_ADDED + " DESC");
        if (cursor != null && cursor.moveToFirst()) {
            do {
                VideosOwn videoval = new VideosOwn(
                        cursor.getLong(cursor.getColumnIndex(MediaStore.Video.Media._ID)),
                        cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.TITLE)),
                        cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.WIDTH)),
                        cursor.getLong(cursor.getColumnIndex(MediaStore.Video.Media.HEIGHT)),
                        cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.ORIENTATION)),
                        cursor.getLong(cursor.getColumnIndex(MediaStore.Video.Media.SIZE))
                );
                videos.add(videoval);
            } while (cursor.moveToNext());
        }
        if (cursor != null) {
            cursor.close();
        }
        return videos;
    }

我是 Rxjava/RxAndroid 的新手,我想将数据作为 ArrayList

如何做到这一点,我们应该使用 DisposalbeObservable.fromCallable,什么是最佳解决方案。

因为你总是想要一个单一的结果,而且它会是一个冷观察,你可以使用 Single,像这些例子:

发射器:

public Single<List<VideosOwn>> getVideos(Context context) {
    return Single.create(emitter -> {
        try {
            final List<VideosOwn> result = GetVideoList(context);
            emitter.onSuccess(result);
        } catch (Exception e) {
            emitter.onError(e);
        }
    });
}

可调用:

public Single<List<VideosOwn>> getVideos(Context context) {
        return Single.fromCallable(() -> GetVideoList(context));
    }

用法:

    // Retain Disposable and call d.dispose() if you no longer want to subscribe to the result
    final Disposable d = getVideos(context)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(r -> {
                // do something with list
            }, e -> {
                // log error or some other handle
            });