RxKotlin icon indicating copy to clipboard operation
RxKotlin copied to clipboard

Need help in type casting when using rxjava in kotlin

Open shakil807g opened this issue 8 years ago • 4 comments

i have some function which is like that

fun getUsers() : Flowable<Response<List<User>>> {
......
}

This is a Extension function

   fun <T> Flowable<Response<T>>.applySchedulers() =
      this.map({ (is_local,message, _, data) ->
      if (data != null)   Success(is_local, message, data)  else Error(message) })
      .onErrorReturn({ t-> Error(t.message!!)})
      .subscribeOn(Schedulers.io())
      .observeOn(AndroidSchedulers.mainThread())
      .startWith(Loading)

but the problem is in calling code where i have to cast it to userList

and from the calling code i am calling it like

 private fun fetchData() {

       dataSource.getUsers()
            .applySchedulers()    ////  **This an Extension Function which is mention above **
            .bindUntilEvent(this, ActivityEvent.DESTROY)
            .subscribe({ t ->
                when (t) {
                    is Success<*> -> {
                    val payload = t.data as? List<User> ?: emptyList<User>()   **I have to cast it to user List**
                        Log.d("users ", " ${payload} ")
                        //adapt.data = payload
                    }
                }
            }, { t -> t.printStackTrace() })

shakil807g avatar Jul 15 '17 09:07 shakil807g

It is because your Success class takes the raw Response.data as its member. I will make the Success class into a Generic class Success<T>, where T is your data's actual type, this way you can always get the exact type without manual casting.

A feedback will be nice if it works.

Edward608 avatar Aug 30 '17 08:08 Edward608

sealed class State
object Loading : State()
data class Error(val msg: String): State()
data class Success<out T>(val islocal :Boolean = false,val msg: String,val data: T?): State()

i am using a state sealed class like this i am already using Success with generic data type for data member variable

shakil807g avatar Aug 30 '17 12:08 shakil807g

Instead of Success<out T>, try Success<T>?

Edward608 avatar Aug 31 '17 03:08 Edward608

Whole sealed class State have to be generic

OrdonTeam avatar Nov 24 '17 12:11 OrdonTeam