Home > Blockchain >  Kotlin - Clarification Needed Regarding the Data Classes Copy Function
Kotlin - Clarification Needed Regarding the Data Classes Copy Function

Time:01-05

Hello everyone I am new to Jetpack Compose. Needed clarification reagarding the usage of Copy Function in kotlin Data Classes.

Here i am using a NetworkFetchState abstract class, which helps me determine the state of the network call.

// Abstract Class

abstract class NetworkFetchState(
 val isLoading: Boolean = false,
 val isSuccess: Boolean = false,
 val isError: Boolean = false,
 val error: Throwable? = null,
 val errorMessage: String? = null
)

I am creating the data class that is extending this abstract class

data class LoginDataState(
    val responseData: LoginResponse? = null
) : NetworkFetchState() // extending the Abstract Class

Now inside the ViewModel Class i am creating a mutable state flow

class MyViewModel:ViewModel(){
 
    // Mutable State Flow of the Data State
    private val _loginDataState = MutableStateFlow(LoginDataState())

    // readonly value of the __loginDataState
    val loginDataState: StateFlow<LoginDataState> get() = _loginDataState

/*
* Here I am performing network calls inside the view model scope
* based on the result from the network call i am trying to update the MutableStateFlow
*/

  fun makeNetworkCall(){
    // ....
    _loginDataState.update { prevState ->
        prevState.copy(
         // ---- PROBLEM HERE ----
         // isLoading, isSuccess.. etc (all other variables from abstract class)
         // are not available
        )
     }
  }

}

all the member variables that are extending from abstract class are not visible.

What am i doing wrong?

CodePudding user response:

The .copy function is a function generated by kotlin compiler for all data classes. As per the documentation, it's using only properties declared in the primary constructor.

If you want to change those properties with copy function, you will have to add them to the primary constructor somehow.

// this would work
data class LoginDataState(
    val responseData: LoginResponse? = null,
    val _isLoading: Boolean = false,
) : NetworkFetchState(isLoading = _isLoading)

// this is probably better
interface NetworkFetchState {
    val isLoading: Boolean get() = false
}

data class LoginDataState(
    val responseData: LoginResponse? = null,
    override val isLoading: Boolean = false,
) : NetworkFetchState
  • Related