When I am calling an API, it loads data into our LazyColumn, but only for the first time. When the user exits the app and comes back immediately, the data is not shown. However, if they come back after a while, the data is shown again.
Additionally, it feels laggy in the LazyColumn, whereas when I call the same API in a RecyclerView, it doesn’t feel laggy.
As I am new to Jetpack Compose, any advice or solutions would be appreciated.
MainActivity
class MainActivity : ComponentActivity() {
private val viewModel: EmployeeViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Surface(
modifier = Modifier.fillMaxSize(),
) {
EmployeeList(viewModel)
}
}
}
}
@Composable
fun EmployeeList(viewModel: EmployeeViewModel) {
LaunchedEffect(Unit) {
viewModel.fetchEmployees()
}
val employee by viewModel.employees.observeAsState()
Box(
modifier = Modifier
.fillMaxSize()
.padding(vertical = 8.dp),
) {
when (val data = employee?.data) {
null -> LoadingIndicator(Modifier.align(Alignment.Center))
else -> {
if (data.any { it.employeeName.isBlank() || it.employeeAge == null || it.employeeSalary == null }) {
Text(
text = "Error: Invalid employee data!",
modifier = Modifier.align(Alignment.Center),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.error
)
} else {
LazyColumn {
items(data, key = { it.id }) { item ->
EmployeeCard(
profileImage = R.drawable.ic_launcher_background,
name = item.employeeName,
age = item.employeeAge.toString(),
salary = item.employeeSalary.toString(),
)
}
}
}
}
}
}
}
Retrofit Instance
object RetrofitInstance {
private const val BASE_URL = "https://dummy.restapiexample.com/api/v1/"
private val retrofit : Retrofit by lazy {
Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
val getEmployeeService : GetEmployeeService by lazy {
retrofit.create(GetEmployeeService::class.java)
}
}
Interface
interface GetEmployeeService {
@GET("employees")
suspend fun getEmployee() : Employee
}
ApiRepository
class ApiRepository {
private val employeeService = RetrofitInstance.getEmployeeService
suspend fun getEmployee() : Employee {
return employeeService.getEmployee()
}
}
ViewModel
class EmployeeViewModel : ViewModel(){
private val apiRepository = ApiRepository()
private val _employees = MutableLiveData<Employee>()
val employees : LiveData<Employee> = _employees
fun fetchEmployees() {
viewModelScope.launch {
try {
val empl = apiRepository.getEmployee()
_employees.value = empl
} catch (e: Exception) {
Log.d("Tag", "fetchEmployees: ${e.message}")
}
}
}
}