我想在 ViewModel 初始化时发出 API 请求。这就是为什么我在方法内部发出 API 请求init;期望在init我在 Activity 中注入 viewModel 时被触发。我究竟做错了什么?
MainViewModel.kt
@HiltViewModel
class MainViewModel @Inject constructor(private val mainRepository: MainRepo) : ViewModel() {
companion object {
var TAG = "MainViewModel**"
}
init {
Log.d(TAG, "NOT TRIGGERED: ")
viewModelScope.launch {
val album1: List<AlbumItem> = mainRepository.getAlbums()
}
}}
Run Code Online (Sandbox Code Playgroud)
MainActivity.kt
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
private val mainViewModel : MainViewModel by viewModels() // injecting viewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding: ActivityMainBinding =
DataBindingUtil.setContentView(this, R.layout.activity_main)
} …Run Code Online (Sandbox Code Playgroud)