Uplaod a file by using RxUploader in Android

Sharing is caring!

RxUploader is reactive uploader for Android by using RxJava and OkHttp. Upload an image or file is widely used in an android application.  But uploading a file or image is not a simple task in android. We have to take care many things before upload. Generally, I would be recommended that upload a file should be in multipart format.  Many of the developers are uploading a file in byte array format which creates a problem if the image size is very large.

Uploading a file or image required a server. If you have not server then Firebase storage is the best alternative to upload a file. Firebase Storage is built for app developers who need to store and serve user-generated content, such as photos or videos. Firebase Storage is a stand-alone solution for uploading user generated content like images and videos from an iOS and Android device, as well as the Web. Here is the tutorial to find to upload a file on Firebase storage.

If you have a server and want to upload a file on the server then you can upload a file in multipart format by suing either Retrofit or Volley networking library. Retrofit works very seamlessly with RxJava. RxAndroid provides the Android Scheduler for scheduling the main thread switch between the threads easily. Here is the tutorial to find to upload a file on the server by using Retrofit in Android.

For RxUplaoder we need Retrofit API service for initialized retrofit.

public final class Service {
    private static final Map<Class<?>, Object> serviceMap = new HashMap<>();

    private Service() {
    }

    @NonNull
    public static ApiService apiService(@NonNull String token, @NonNull String secret) {
        ApiService s = (ApiService) serviceMap.get(ApiService.class);
        if (s == null) {
            s = createService(ApiService.class, token, secret);
            serviceMap.put(ApiService.class, s);
        }
        return s;
    }

    @NonNull
    private static <S> S createService(@NonNull Class<S> s, @NonNull String token,
            @NonNull String secret) {
        final GsonConverterFactory serializer = GsonConverterFactory.create(
                new GsonBuilder().registerTypeAdapterFactory(JSONModelTypeAdapterFactory.create())
                        .create());

        final OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        OkHttpOAuthConsumer consumer = new OkHttpOAuthConsumer(
                Config.CONSUMER_KEY, Config.CONSUMER_SECRET);
        consumer.setTokenWithSecret(token, secret);
        httpClient.addInterceptor(new SigningInterceptor(consumer));

        final HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(Config.HTTP_LOG_LEVEL);
        httpClient.addInterceptor(loggingInterceptor);

        final Retrofit client = new Retrofit.Builder().baseUrl(Config.HOST)
                .addConverterFactory(serializer)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(httpClient.build())
                .build();
        return client.create(s);
    }
}

and required interface ApiService is:

public interface ApiService {
    @NonNull
    @GET("v1/photos?feature=user")
    Observable<PhotosJSONModel> getPhotos(@Query("username") @NonNull String username);

    @NonNull
    @Multipart
    @POST("v1/photos/upload")
    Observable<UploadPhotoJSONModel> uploadPhoto(@Query("name") @NonNull String name,
            @Query("description") @NonNull String description, @Query("privacy") int privacy,
            @Part @NonNull MultipartBody.Part photo);
}

Now we need to get the UploadManager build instance to execute this service job for upload. Here we need to get CompositeSubscription for checking the status of upload if the subscription is alive.

subscriptions = new CompositeSubscription();
apiService = Service.apiService(token, secret);
uploadManager = UploadManager.builder()
                .withSimpleUploadDataStore(this)
                .withUploadService(PhotoUploadService.create(apiService))
                .withUploadErrorAdapter(new PhotoUploadErrorAdapter())
                .build();
subscriptions.add(uploadManager.status()
                .flatMap(status -> {
                    final String jobId = status.id();
                    return uploadManager.getJob(jobId)
                            .filter(job -> !Job.isInvalid(job))
                            .map(job -> job.withStatus(status));
                })
                .map(job -> {
                    final Map<String, Object> metadata = job.metadata();
                    final String name = StringUtils.getOrEmpty((String) metadata.get("name"));
                    final String description = StringUtils
                            .getOrEmpty((String) metadata.get("description"));
                    return UploadDataModel.create(name, description, job.status());
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(model -> {
                    final Status status = model.getStatus();
                    if (status.statusType() == StatusType.COMPLETED) {
                        // Success
                    } else {
                       // failed
                    }
        }));

Here you can get the sample of RxUploader full source code access.

Please do subscribe your email to get every newsletter from this blog and if you feel that this post helps you then do not forget to share and comment below.

Happy Coding 🙂

0 0 votes
Article Rating
Uplaod a file by using RxUploader in Android
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Scroll to top
0
Would love your thoughts, please comment.x
()
x