0

I have an android app that makes a Retrofit service call uploadPhoto after the button click.

In this service call response I would like to receive a photo ID so I need to listen to the service response or error. I have the code that handles this

Signletons.retrofitService.uploadPhoto(photoData)
                    .subscribe(new Action1<Response<UploadResponse>>() {
                        @Override
                        public void call(Response<UploadResponse> response) {
                            // response.body().photoId
                        }
                    })

But when activity gets destroyed due to the orientation change, I unsubscribe from the above Observable and this may happen somewhere between my photo request was sent, but before the response is received. This means that I may upload the photo, but not get the photo ID.

What is the best way to handle this situation and to resubscribe after orientation changes to get the result I missed due to the orientation change?

Sergei Ledvanov
  • 2,131
  • 6
  • 29
  • 52

2 Answers2

0

since you want to continue the upload of the image independant from the activity, it might make sense to store the subscription in location that has a longer / different life-time, e.g. as part of your Signletons and handle the subscription manually. Then, after the orientation change, check for an active subscription:

if (Signletons.uploadSubscription != null) { 
    activeUploadSub = Signletons.uploadSubscription
}

another solution would be to avoid destroying the activity for orientation changes by adding an attribute to the activity in your app's manifest:

android:configChanges="orientation|screenSize"
nosyjoe
  • 551
  • 2
  • 10
-1

According to this answer , just unsubscribe if the activity is not finished

 @Override
 protected void onDestroy() {
     super.onDestroy();
    if (isFinishing()) {
        subscription.unsubscribe();
    } else { 
       //It's an orientation change.
    }
  }
Community
  • 1
  • 1
dwursteisen
  • 11,435
  • 2
  • 39
  • 36
  • How does it help to re-subscribe when activity is re-created again? – Sergei Ledvanov Aug 09 '16 at 11:53
  • you're right. It won't help. You may not subscribe again to the Observable in the onCreate method, as the previous one ins't unsubscribed. – dwursteisen Aug 09 '16 at 11:56
  • If I won't unsubscribe from this observable, then this observable's handler will stay in the activity that will be destroyed. When the result arrives, there would be no point of handling it in the activity that is destroyed. Even more, holding activity from being destroyed is a very expensive operation. – Sergei Ledvanov Aug 09 '16 at 15:41