Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Need help in type casting when using rxjava in kotlin #138

Open
shakil807g opened this issue Jul 15, 2017 · 4 comments
Open

Need help in type casting when using rxjava in kotlin #138

shakil807g opened this issue Jul 15, 2017 · 4 comments

Comments

@shakil807g
Copy link

shakil807g commented Jul 15, 2017

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() })
@Edward608
Copy link

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, 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.

@shakil807g
Copy link
Author

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

@Edward608
Copy link

Edward608 commented Aug 31, 2017

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

@OrdonTeam
Copy link
Contributor

Whole sealed class State have to be generic

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants