我如何通过RxJava2在android中实现这一目标?

时间:2018-01-22 10:29:43

标签: android firebase rx-java firebase-storage rx-java2

我正在尝试将图片上传到Firebase存储,我想通过RxJava2实现这一目标。这是我的代码..

public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {

    if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
        val result = CropImage.getActivityResult(data)
        if (resultCode == Activity.RESULT_OK) {
            val resultUri = result.uri
            var actualImageFile = File(resultUri.path)
            dialogs = SpotsDialog(this, "upload")
            imageCompressor = Compressor(this)
            var image_bitmap = imageCompressor
                    ?.setMaxWidth(200)
                    ?.setMaxHeight(200)
                    ?.setQuality(75)
                    ?.compressToBitmap(actualImageFile)
            profile_image?.setImageBitmap(image_bitmap)
            dialogs?.show()
            try{
            FirebaseStorage.getInstance().reference.child("profile_images").child(FirebaseAuth.getInstance().currentUser?.uid + ".jpg").putFile(resultUri)
                    .addOnCompleteListener { task: Task<UploadTask.TaskSnapshot> ->
                        if (task.isSuccessful) {
                            showMessage("image uploaded")
                            val baos = ByteArrayOutputStream()
                            image_bitmap?.compress(Bitmap.CompressFormat.JPEG, 100, baos)
                            FirebaseStorage.getInstance().reference.child("profile_images").child("thumbs_images").child(FirebaseAuth.getInstance().currentUser?.uid + ".jpg").putBytes(baos.toByteArray())
                                    .addOnCompleteListener { t ->
                                        if (t.isSuccessful) {
                                            dialogs?.dismiss()
                                            showMessage("thumbnail uploaded")
                                        } else {
                                            dialogs?.dismiss()
                                            showMessage("thumbnail error")
                                        }
                                    }
                        } else {
                            showMessage("image error")
                            dialogs?.dismiss()
                        }
                    }
        }catch(es : Exception){
            es.printStackTrace()
        }
        }else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
            val error = result.error
        }
    }
}

我想通过RxJava2做同样的事情,但我不知道该怎么做..请告诉我。提前致谢

2 个答案:

答案 0 :(得分:2)

您不需要在此过程中使用任何库,如果您只需要将对Firebase的调用包装到RxJava调用中,我就会这样做:

这是您上传文件的第一个外部呼叫

fun firebaseFileUploader(uri: Uri) : Single<String> {
return Single.create{ subscriber ->
    FirebaseStorage.getInstance()
            .reference
            .child("profile_images")
            .child("${FirebaseAuth.getInstance().currentUser?.uid}.jpg")
            .putFile(uri)
            .addOnCompleteListener {
                if(it.isSuccessful) {
                    if(!subscriber.isDisposed) {
                        subscriber.onSuccess("Image uploaded")
                    }
                } else {
                    subscriber.onError(Throwable("Error uploading file to firebase, Image Error"))
                }
            }
}

这是您第二次上传缩略图

fun firebaseBytesUploader(baos: ByteArrayOutputStream) : Single<String> {
return Single.create { subscriber ->
    FirebaseStorage.getInstance()
            .reference
            .child("profile_images")
            .child("thumbs_images")
            .child("${FirebaseAuth.getInstance().currentUser?.uid}.jpg")
            .putBytes(baos.toByteArray())
            .addOnCompleteListener {
                if(it.isSuccessful) {
                    if(!subscriber.isDisposed) {
                        subscriber.onSuccess("Thumbnail uploaded")
                    }
                } else {
                    subscriber.onError(Throwable("Error uploading thumbnail"))
                }
            }
}

这是启动该过程的方法,它会返回一个一次性的,以便您可以处理此流以防万一您的活动被破坏等等。

fun startuploadRx(uri: Uri, baos: ByteArrayOutputStream) : Disposable {
return firebaseFileUploader(uri)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .flatMap {
            firebaseBytesUploader(baos).subscribeOn(Schedulers.io())
        }
        .doOnSubscribe {
            //show loading dialog
        }
        .doAfterTerminate {
            //dismiss loading dialog
        }
        .subscribe({successMessage ->
            //do something with the success message
        }, {
           //do something with the error message
        })

这只是一个例子,它并不完美,但是一个好的起点。希望它有所帮助!

答案 1 :(得分:0)

使用此library

RxFirebaseStorage.putFile(
        FirebaseStorage.getInstance().reference.child("profile_images")
            .child(FirebaseAuth.getInstance().currentUser?.uid + ".jpg"), resultUri
    )
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe({
            showMessage("image uploaded")
            val baos = ByteArrayOutputStream()
            image_bitmap?.compress(Bitmap.CompressFormat.JPEG, 100, baos)
            RxFirebaseStorage.putBytes(
                FirebaseStorage.getInstance().reference.child("profile_images")
                    .child("thumbs_images")
                    .child(FirebaseAuth.getInstance().currentUser?.uid + ".jpg"),
                baos.toByteArray()
            )
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    {
                        dialogs?.dismiss()
                        showMessage("thumbnail uploaded")
                    }, {
                        dialogs?.dismiss()
                        showMessage("thumbnail error")
                    }
                )
        }, {
            showMessage("image error")
            dialogs?.dismiss()
        })

您可能需要根据项目进行调整,但您明白了。