Mattwalk
Mattwalk

Reputation: 139

How can i achieve this by RxJava2 in android?

I am trying to upload images to Firebase Storage and i wanna achieve this thing by RxJava2. Here is my code..

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
        }
    }
}

I wanna do the same by RxJava2 but I'm not getting how to do it.. Please tell me . Thanks in advance

Upvotes: 1

Views: 638

Answers (2)

arubin
arubin

Reputation: 146

You don't need to use any libraries to this process, this is how I would do it if you just needed to wrap the calls to Firebase into RxJava calls:

This is your first outer call that you make to upload the file

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"))
                }
            }
}

This is your second call to upload the thumbnail

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"))
                }
            }
}

This is the method to start the process, it returns you a disposable so you can dispose of this stream in case your activity gets destroyed, etc.

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
        })

Again this is just an example, it's not perfect, but a good place to start. Hope it helps!

Upvotes: 5

Benjamin
Benjamin

Reputation: 7368

Using this 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()
        })

You might have to adapt this to your project but you got the idea.

Upvotes: 0

Related Questions