Dante313
Dante313

Reputation: 301

How to set type to generic?

I have this generic in seald class:

sealed class ResponseResult {
    class Success<T>(val data: T, val city: String) : ResponseResult()
}

I'm setting my Response<Weather> body in this Success class with succesful call in my ViewModel:

if (response.isSuccessful) {
   response.body().let {
   _screenState.postValue(ResponseResult.Success(it, cityName))
}

but when i'm trying to get fields from my Weather array (which is Response type of) in fragment i can't get them because my type is Any.

viewModel.screenState.observe(viewLifecycleOwner) {
            when (it) {
                is ResponseResult.Success<*> -> {
                    setSuccessResult()
                    it.data.
                }

How can i make my generic understand that this is type of "Weather"?

Upvotes: 0

Views: 72

Answers (1)

Taha K&#246;rkem
Taha K&#246;rkem

Reputation: 906

Try the following code

sealed class ResponseResult<T> {
    class Success<T>(val data: T, val city: String) : ResponseResult<T>()
}

In your view model

val _screenState = MutableLiveData<ResponseResult<Weather>>()

In your fragment

viewModel.screenState.observe(viewLifecycleOwner) {
        when (it) {
            is ResponseResult.Success -> {
                setSuccessResult()
                val data: Weather = it.data
                //use data the way you want
            }
}

Upvotes: 1

Related Questions