Need help in type casting when using rxjava in kotlin
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() })
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.
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
Instead of Success<out T>, try Success<T>?
Whole sealed class State have to be generic