Home > Blockchain >  Is this a correct usage of let function?
Is this a correct usage of let function?

Time:08-07

currently learning android development (Kotlin).

i wonder if it's a correct usage of let function.

viewModelScope.launch(Dispatchers.IO) {
        val response = RetrofitHelper.getRealEstateService().getRealEstateModel()
        response.body()?.let {
            if(response.isSuccessful){
                val data = response.body()
                _data.emit(data?.content?: emptyList())
            }
        }
    }

previously i was checking if the value is null in a normal way like this:

if(response.isSuccessful && response.body() != null){
            val data = response.body()
            _data.emit(data?.content?: emptyList())
        }

so i just changed null check with let function.

Thanks!

CodePudding user response:

This is a common pattern for dealing with nulls, however, it probably makes more sense to use parameter passed to let lambda, as it already contains a non-nullable response body:

response.body()?.let { data ->
    if(response.isSuccessful){
        _data.emit(data.content?: emptyList())
    }
}

This way we don't have to acquire body() twice and then deal with nullable value.

  • Related