https://kotlinlang.org logo
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
benchmarks
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
confetti
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
lincheck
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by
Title
x

xetra11

11/28/2020, 8:36 PM
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

Timo Drick

11/28/2020, 10:17 PM
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

Igor Demin

11/29/2020, 10:59 AM
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):
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

Timo Drick

11/29/2020, 12:53 PM
Not necessary to use the coroutine scope of the view. So you can just do this:
@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

Igor Demin

11/29/2020, 1:36 PM
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

Timo Drick

11/29/2020, 7:32 PM
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.
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

Igor Demin

11/29/2020, 8:08 PM
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.
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

Timo Drick

11/30/2020, 12:39 AM
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

Igor Demin

11/30/2020, 7:55 AM
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

Timo Drick

11/30/2020, 3:38 PM
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.