oligazar
8/14/2017 - 9:51 AM

Rxjava2 + Retrofit2 examples https://blog.kaush.co/2017/06/21/rxjava1-rxjava2-migration-understanding-changes/


    /* Rx - reactive extensions
            * https://github.com/ReactiveX/RxAndroid */
    compile "io.reactivex.rxjava2:rxandroid:2.0.1"
    compile "io.reactivex.rxjava2:rxjava:2.1.2"
    
    // rx lint checks
    compile "nl.littlerobots.rxlint:rxlint:1.0"

    /* Retrofit - networking
            * http://square.github.io/retrofit/ */
    compile "com.squareup.retrofit2:retrofit:$rootProject.ext.retrofit2Version"
    compile "com.squareup.retrofit2:converter-gson:$rootProject.ext.retrofit2Version"
    compile "com.squareup.retrofit2:adapter-rxjava2:$rootProject.ext.retrofit2Version"
// for Observable
(activity.application as MyApp).api
                .postGetVoucher(GetVoucherBody(getToken(activity.getPreferences()), voucherNum))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : SingleObserver<Order> {

                    override fun onSuccess(order: Order) {
                        dialog.dismiss()

                        Log.d("ScanFragment", "Order: $order")
                        if (order.error == null) {
                          ...
                        } else {
                          ...
                        }
                    }

                    override fun onSubscribe(d: Disposable) {
                        compositeSubscription?.add(d)
                    }

                    override fun onError(e: Throwable) {
                        dialog.dismiss()
                        e.printStackTrace()
                    }
                })
    }
    
    
// or for Single

(activity.application as MyApp).api
                .postGetVoucher(GetVoucherBody(getToken(activity.getPreferences()), voucherNum))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : SingleObserver<Order> {

                    override fun onSuccess(order: Order) {
                        dialog.dismiss()

                        if (order.error == null) {
                           ...
                        } else {
                          ...
                        }
                    }

                    override fun onSubscribe(d: Disposable) {
                        compositeSubscription?.add(d)
                    }

                    override fun onError(e: Throwable) {
                        dialog.dismiss()
                        e.printStackTrace()
                    }
                })
    }
    
// or even simpler

val subscription = (activity.application as MyApp).api
                .postGetVoucher(GetVoucherBody(getToken(activity.getPreferences()), rawResult.text))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ order ->
                    dialog.dismiss()

                    Log.d("ScanFragment", "Order: $order")
                    if (order.error == null) {
                        realm.executeTransaction {
                            realm.copyToRealmOrUpdate(order)
                        }
                        when (order.status) {
                            completed.name -> fragmentManager.replace(R.id.content, ErrorFragment
                                    .newInstance(getString(R.string.error_message_completed)),
                                    order.toString())
                            paid.name -> fragmentManager.replace(R.id.content, ClientInfoFragment.newInstance(order.id))
                            canceled.name -> fragmentManager.replace(R.id.content, ErrorFragment
                                    .newInstance(getString(R.string.error_message_canceled)))
                            else -> fragmentManager.replace(R.id.content, ErrorFragment
                                    .newInstance(getString(R.string.error_message_other)))
                        }
                    } else {
                        fragmentManager.replace(R.id.content, ErrorFragment.newInstance(order.error?.descr ?: getString(R.string.error_message_default)))
                    }
                }, { error ->
                        dialog.dismiss()
                        error.printStackTrace()
                })
        compositeSubscription?.add(subscription)
    
    
// in Application subclass
    private fun createApiInterface(): ApiInterface {
        val gson = GsonBuilder()
                .registerTypeAdapter(Order::class.java, OrderModelDeserializer())
                .registerTypeAdapter(Contacts::class.java, ContactsModelDeserializer())
                .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
                .create()

        val cacheSize = 10 * 1024 * 1024 // 10 MiB
        val cache = Cache(cacheDir, cacheSize.toLong())
        val okHttpClient = StethoUtils.getOkHttpClient(cache)

        val retrofit = Retrofit.Builder()
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create(gson))
                .baseUrl(MyApp.BASE_URL)
                .client(okHttpClient)
                .build()

        return retrofit.create(ApiInterface::class.java)
    }