android 如何用RxJava Single〈> Package Firebase OnCompleteListener?

vhmi4jdf  于 2023-01-19  发布在  Android
关注(0)|答案(1)|浏览(142)

我正在使用Firebase上传一张图片,我正在使用Firebase的.onCompleteListener()在回调函数中获取上传图片的URL。
我试图将其合并到我的Repository类中,但我不确定如何操作。
有人能帮我找出我做错了什么吗?

public Single<String> uploadImage(String path) {
        Uri uri = Uri.fromFile(new File(path));
        String fileName = createNewFileName(uri);
        StorageReference ref = firebaseStorage.getReference().child(fileName);

        return Single.fromCallable(() -> {
            UploadTask uploadTask = ref.putFile(uri);
            uploadTask.continueWithTask(task -> {
                if (!task.isSuccessful()) {
                    throw task.getException();
                }
                return ref.getDownloadUrl();
            }).addOnCompleteListener(task -> {
                if (task.isSuccessful()) {
                    Uri downloadUri = task.getResult();
                    String url = downloadUri.toString();
                    
                    //String to use in Single<>
                } else {
                    //Handle Error
                }
            });
        });

    }

在我的ViewModel中使用

uploadImage(path)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(url -> {
                    
        }, err -> {
                    
        });
dw1jzc5e

dw1jzc5e1#

您需要Single.create
提供一个API(通过一个冷Single),将React式世界与回调风格世界连接起来。

return Single.<String>create(emitter -> {
            UploadTask uploadTask = ref.putFile(uri);
            uploadTask.continueWithTask(task -> {
                if (!task.isSuccessful()) {
                    throw task.getException();
                }
                return ref.getDownloadUrl();
            }).addOnCompleteListener(task -> {
                if (task.isSuccessful()) {
                    Uri downloadUri = task.getResult();
                    String url = downloadUri.toString();
                    
                    emitter.onSuccess(url);
                } else {
                    emitter.onError(task.getException());
                }
            });
        });

相关问题