I am working on a project and I want to fetch the data from Api and display it in UI. I am using Jetpack Compose by the way. How can I call the suspend function in Main Activity? I want to fetch the list and then call the function bookListScreen(bookList : BookList) in LotrAppTheme{}. How can I do this?
Main Activity:
package com.example.lotrapp
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
private val bookViewModel: BookViewModel by viewModels()
private lateinit var bookList : BookList
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
LOTRAppTheme {
}
}
}
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
LOTRAppTheme {
}
}
View Model:
package com.example.lotrapp
import androidx.lifecycle.ViewModel
import com.example.lotrapp.models.BookList
import com.example.lotrapp.repository.BookRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class BookViewModel @Inject constructor(
private val repository: BookRepository
) : ViewModel() {
suspend fun getBookList() : BookList? {
return repository.getBookList()
}
}
BookListScreen
@Composable
fun bookListScreen(bookList : BookList) {
Column(
modifier = Modifier
.fillMaxSize()
.background(Color.Gray)
) {
LazyColumn(
contentPadding = PaddingValues(all = 12.dp),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
itemsIndexed(
items = bookList.docs
) {
index, book -> BookItem(book)
}
}
}
}