What is the best practice to have for instance a "...
# compose-desktop
x
What is the best practice to have for instance a "Load Textfile" option in the MenuBar but having the loaded file being displayed in a view? My problem is I have no idea how to share a mutableState between the MenuItem scope and the main view scope of the app
t
I think the best practice (Just in my opinion because CfD is so new that there is no best practive :-D) would be that you write your text view component so that it gets the text to display as parameter. So your Main view component holds the state and than the menu changes it.
👍 1
👆 3
When you have more states in your main view composition you can also create a class which holds all states and share this class with every view component that needs access. But of course you could also define this class in global scope. Also not so bad i think.
👍 1
StateProvider is a little bit more complex but maybe better solution than having a global singleton. But in my opinion the readablity of the code will be worse.
i
create a class which holds all states and share this class with every view component that needs access
I would implement something like this (split implementation into View/Model):
Copy code
import androidx.compose.desktop.AppManager
import androidx.compose.desktop.Window
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.onActive
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import <http://androidx.compose.ui.window.Menu|androidx.compose.ui.window.Menu>
import androidx.compose.ui.window.MenuBar
import androidx.compose.ui.window.MenuItem
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File
import javax.swing.UIManager

fun main() {
    System.setProperty("apple.laf.useScreenMenuBar", "true")
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName())

    val model = TextViewer()

    initMenu(model)

    Window {
        TextViewerView(model)
    }
}

private fun initMenu(textViewer: TextViewer) {
    AppManager.setMenu(
        MenuBar(
            Menu(
                name = "File",
                MenuItem(
                    name = "Open",
                    onClick = {
                        textViewer.loadFile(File("D:/1.txt"))
                    }
                ),
            )
        )
    )
}

@Composable
fun TextViewerView(textViewer: TextViewer) {
    val scope = rememberCoroutineScope()

    onActive {
        textViewer.scope = scope

        onDispose {
            textViewer.scope = null
        }
    }

    Text(textViewer.text)
}

class TextViewer {
    var text by mutableStateOf("")

    var scope: CoroutineScope? = null

    fun loadFile(file: File) {
        scope?.launch(<http://Dispatchers.IO|Dispatchers.IO>) {
            text = file.readText()
        }
    }
}
t
Not necessary to use the coroutine scope of the view. So you can just do this:
Copy code
@Composable
fun TextViewerView(textViewer: TextViewer) {
    Text(textViewer.text)
}
class TextViewer {
    var text by mutableStateOf("")
    fun loadFile(file: File) {
        GlobalScope.launch(<http://Dispatchers.IO|Dispatchers.IO>) {
            text = file.readText()
        }
    }
}
i
Not necessary to use the coroutine scope of the view.
It is good thing if we cancel coroutineScope (and also file loading) if we leave Composable view. We can use own coroutineScope inside TextViewer, but we should cancel it if we leave Composable (or close the window)
t
Ok but your solution is very likely to fail. Likelyhood for errors is to high and too complicated. So you should think of livecycle but don't do it this way. You could e.g. add a cancel method to the TextViewer which you call at onDispose which will cancel the GlobalScope coroutine.
Copy code
fun main() {
    System.setProperty("apple.laf.useScreenMenuBar", "true")
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName())
    val model = TextViewer()
    initMenu(model)
    Window {
        TextViewerView(model)
        onDispose {
            model.cancel()
        }
    }
}private fun initMenu(textViewer: TextViewer) {
    AppManager.setMenu(
        MenuBar(
            Menu(
                name = "File",
                MenuItem(
                    name = "Open",
                    onClick = {
                        textViewer.loadFile(File("D:/1.txt"))
                    }
                ),
            )
        )
    )
}
@Composable
fun TextViewerView(textViewer: TextViewer) {
    Text(textViewer.text)
}
class TextViewer : CoroutineScope {
    private val job = Job()
    override val coroutineContext = Dispatchers.Main + job

    var text by mutableStateOf("")
    fun loadFile(file: File) {
        launch(<http://Dispatchers.IO|Dispatchers.IO>) {
            text = file.readText()
        }
    }
    fun cancel() {
        job.cancel()
    }
}
👍 1
i
Yes, my first solution isn't pretty 🙂 . But how about this? We still use Composable scope and don't have to manually handle disposing and care about what Dispatcher to use.
Copy code
fun main() = Window {
    val scope = rememberCoroutineScope()
    val model = remember { TextViewer(scope) }
    onActive {
        initMenu(model)
    }
    TextViewerView(model)
}

@Composable
fun TextViewerView(textViewer: TextViewer) {
    Text(textViewer.text)
}

class TextViewer(private val scope: CoroutineScope) {
    var text by mutableStateOf("")

    fun loadFile(file: File) {
        scope.launch(<http://Dispatchers.IO|Dispatchers.IO>) {
            text = file.readText()
        }
    }
}
t
Your model should be independent from the view. You could also just make the loadFile function a suspend function. But than you have to solve the scope problem at the onClick method.
i
Your model should be independent from the view
It is. But it should live only if Composable view lives. So we can manually create/dispose it in Composable or just use already suitable scope and inject it into the model during its construction. It is controversial architectural question, there is approaches when the model is created indirectly, outside of the view, and the view is just a visual mirror of the model.
It is not like ViewModel/View(Fragment) from Android world, where is ViewModel lives longer than the view (and ViewModel shouldn't references any view objects like Context). In Compose for Desktop we can implement different architecture. (on Android it is also possible, because Compose is very convenient for handling rotations/configuration changes)
But if we have multiple screens, we might want to keep the model alive, and destroy Composable view (to free resources, because view can hold heavy bitmaps). So in this case we can initialize our model inside some navigation classes and pass "screen scope" that is alive if screen is in the backstack.
t
In my opinion robust and simple (KISS) code is much more important than trying to implement a special architecture pattern or philosophy. In your case the TextView model component can live the whole lifespan of the app. Because you do nothing else. Later you could devide your app into seperate modules and only load models which are currently necessary.
In Android you do this with the ViewModel but i think this do not exist for CfD. But maybe you could develop s.th. similar with several lines of code.