Class Response

  • All Implemented Interfaces:

    
    public class Response<T extends Object>
    
                        

    A generic class that holds a value with its loading status. Can be used to represent any operation that can be in one of the following states: Loading, Success, Error.

    fun example() { // With data val responseWithData: Response<String> = Response.Success("Hello")

    // Empty success
    val emptyResponse: Response<String> = Response.SuccessEmpty
    // Or using convenience constructor
    val anotherEmptyResponse: Response<String> = Response.success()
    
    // Handling all cases
    when (response) {
        is Response.Success -> println("Success with data: ${response.data}")
        is Response.SuccessEmpty -> println("Success with no data")
        is Response.Error -> println("Error: ${response.exception.message}")
        is Response.Loading -> println("Loading...")
    }
    
    // Using handlers
    response
        .onSuccess { data -> println("Success: $data") }
        .onSuccessEmpty { println("Success with no data") }
        .onError { error -> println("Error: ${error.message}") }
        .onLoading { println("Loading...") }

    }