Simplify ToolWindowFactory.createToolWindowContent implementation with more explicit ViewModel instantiation

This commit is contained in:
Yuriy Artamonov 2025-08-30 10:26:46 +02:00
parent 5d5ef16235
commit bc0c159668

View File

@ -1,39 +1,38 @@
package org.jetbrains.plugins.template.toolWindow
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.remember
import com.intellij.openapi.components.service
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowFactory
import kotlinx.coroutines.Dispatchers
import org.jetbrains.jewel.bridge.addComposeTab
import org.jetbrains.plugins.template.CoroutineScopeHolder
import org.jetbrains.plugins.template.ui.ChatAppSample
import org.jetbrains.plugins.template.weatherApp.model.Location
import org.jetbrains.plugins.template.weatherApp.services.LocationsProvider
import org.jetbrains.plugins.template.weatherApp.ui.WeatherAppViewModel
import org.jetbrains.plugins.template.weatherApp.services.WeatherForecastService
import org.jetbrains.plugins.template.weatherApp.ui.WeatherAppSample
import org.jetbrains.plugins.template.weatherApp.ui.WeatherAppViewModel
class ComposeSamplesToolWindowFactory : ToolWindowFactory, DumbAware {
override fun shouldBeAvailable(project: Project) = true
override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) {
val coroutineScopeHolder = project.service<CoroutineScopeHolder>()
toolWindow.addComposeTab("Weather App") {
val locationProviderApi = remember { service<LocationsProvider>() }
val viewModel = remember {
val weatherForecastServiceApi = WeatherForecastService(Dispatchers.IO)
WeatherAppViewModel(
listOf(Location("Munich", "Germany")),
coroutineScopeHolder
.createScope(WeatherAppViewModel::class.java.simpleName),
weatherForecastServiceApi
)
weatherApp(project, toolWindow)
chatApp(project, toolWindow)
}
private fun weatherApp(project: Project, toolWindow: ToolWindow) {
// create ViewModel once per tool window
val viewModel = WeatherAppViewModel(
listOf(Location("Munich", "Germany")),
project.service<CoroutineScopeHolder>()
.createScope(WeatherAppViewModel::class.java.simpleName),
WeatherForecastService()
)
toolWindow.addComposeTab("Weather App") {
DisposableEffect(Unit) {
viewModel.onReloadWeatherForecast()
@ -43,12 +42,14 @@ class ComposeSamplesToolWindowFactory : ToolWindowFactory, DumbAware {
WeatherAppSample(
viewModel,
viewModel,
locationProviderApi
service<LocationsProvider>()
)
}
toolWindow.addComposeTab("Chat App") { ChatAppSample() }
}
override fun shouldBeAvailable(project: Project) = true
private fun chatApp(project: Project, toolWindow: ToolWindow) {
toolWindow.addComposeTab("Chat App") {
ChatAppSample()
}
}
}