Skip to content

Monitor Uploads

Alex Gotev edited this page Mar 11, 2020 · 30 revisions

When you make an UploadRequest, you get the notification and the progress displayed for free, but in many cases you need to display progress also inside your app screens. This is achieved using the RequestObserver.

The RequestObserver

The RequestObserver is a lifecycle-aware BroadcastReceiver which receives events coming from single or multiple upload requests. It can be used inside Service, Fragment, Activity or globally in your app, depending on your specific need.

Subscribing to an upload request

The easiest and most concise way of monitoring an upload is to subscribe to it. In this way the RequestObserver will receive events only from the subscribed upload request. Simple example with a MultipartUploadRequest.

fun upload(context: Context, lifecycleOwner: LifecycleOwner) {
    MultipartUploadRequest(this, "https://server.url")
        .addFileToUpload(filePath = "/path/to/file", parameterName = "myFile")
        .subscribe(context = context, lifecycleOwner = lifecycleOwner, delegate = object : RequestObserverDelegate() {
            override fun onProgress(context: Context, uploadInfo: UploadInfo) {
                // do your thing
            }

            override fun onSuccess(
                context: Context,
                uploadInfo: UploadInfo,
                serverResponse: ServerResponse
            ) {
                // do your thing
            }

            override fun onError(
                context: Context,
                uploadInfo: UploadInfo,
                exception: Throwable
            ) {
                // do your thing
            }

            override fun onCompleted(context: Context, uploadInfo: UploadInfo) {
                // do your thing
            }

            override fun onCompletedWhileNotObserving() {
                // do your thing
            }
        })
}

From Activity

Supposing you're using the above example function.

class MyActivity : AppCompatActivity() {
   fun myAction() {
       upload(context = this, lifecycleOwner = this)
   }

   fun upload(context: Context, lifecycleOwner: LifecycleOwner) { ... }
}

From Fragment

Supposing you're using the above example function.

class MyFragment: Fragment() {
    fun myAction() {
        upload(context = requireContext(), lifecycleOwner = viewLifecycleOwner)
    }

    fun upload(context: Context, lifecycleOwner: LifecycleOwner) { ... }
}

From Service

Supposing you're using the above example function.

class MyService : LifecycleService() {
    fun myAction() {
        upload(context = this, lifecycleOwner = this)
    }

    fun upload(context: Context, lifecycleOwner: LifecycleOwner) { ... }
}