https://kotlinlang.org logo
Join the conversationJoin Slack
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
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
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
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 Linen
android-architecture
  • h

    Hakob Astvacatryan

    01/30/2020, 10:04 PM
    Hi guys, how you managed having ~15 LiveData in one view-model? Have events that could initiate 4-5 LiveData updates.
    t
    a
    +7
    • 10
    • 37
  • d

    dave08

    02/03/2020, 4:13 PM
    I guess the easiest way is having a
    lateinit var
    that's initialized when the viewmodel is injected in the Fragment... but that's a bit of a brittle way to do things?
    s
    h
    a
    • 4
    • 22
  • o

    Olenyov Kirill

    02/03/2020, 5:38 PM
    Hi, I have a question regarding unidirectional data flow or MVI. About Store component. I know there is a solution when Android app has only one Store. What’s the right way? Many stores per feature/screen or one store for whole app?
    g
    • 2
    • 2
  • a

    amar_1995

    02/05/2020, 7:08 AM
    I read about android single source of truth to provide offline data. But how to deal with post, patch request?
    t
    u
    • 3
    • 4
  • u

    ursus

    02/06/2020, 7:00 PM
    Yea automatic versioning. Which channel is better?
    s
    i
    t
    • 4
    • 24
  • o

    Ofir Bar

    02/09/2020, 10:33 AM
    Hey guys, I am a junior developer and at work we have a screen where the user input basic details about himself: Firstname, Lastname, phone,etc. The UI updates the ViewModel when the “continue” button in the UI is tapped. I wonder if we “over-engineer” our ViewModel or is it just me having it hard to grasp. This is the ViewModel:
    class BasicDetailsViewModel (private val basicDetailsRepository: BasicDetailsRepository) : ViewModel() {
    
        val mUserBasicDetailsPlaceHolderData = basicDetailsRepository.getBasicUserDetailsPlaceholderViaIdentityProvider()
        private val mUserBasicDetailsRequestData: MutableLiveData<UserBasicDetailsRequest> = MutableLiveData()
    
        /**
         * Upon the user taps the continue button, we update [mUserBasicDetailsRequestData]
         * with the data the user has input.
         */
        fun onContinueClicked(firstName: String, lastName: String, phone: String, profileImageUrl: String) {
            mUserBasicDetailsRequestData.value = UserBasicDetailsRequest(firstName, lastName, phone, profileImageUrl)
        }
    
        var updateUserRequest: LiveData<NetworkCall<User>> = mUserBasicDetailsRequestData.switchMap { data ->
            liveData(<http://Dispatchers.IO|Dispatchers.IO>) {
                emit(NetworkCall<User>(NetworkStatus.LOADING, null, ""))
                val updatedUser = basicDetailsRepository.updateUserBasicDetails(data)
                emit(updatedUser)
            }
        }
    After the user input his basic data and taps the “continue” button in the UI, the following happens: • The value “mUserBasicDetailsRequestData” in the ViewModel is changed with the data sent from the UI. • The value “updateUserRequest” in the ViewModel is observing mUserBasicDetailsRequestData, and gets triggered using “switchMap” which I find somewhat confusing. • “updateUserRequest”, upon triggered, updates our backend with the basic user data, and notify the UI that the backend has successfully received our user basic details. In the UI, we then observe updateUserRequest:
    mViewModel.updateUserRequest.observe(this, Observer<NetworkCall<UpdateExpertiseFieldsResponse>> { networkCall ->
        when (networkCall.status) {
            NetworkStatus.SUCCESS -> handleSuccess() //Hide loader & do something.
            NetworkStatus.ERROR -> handleError(networkCall.message ?: getString(R.string.authentication_general_error)) //Hide loader & show error to the user.
            NetworkStatus.LOADING -> showLoader() //Show loader.
        }
    })
    I wonder, is there a special reason that we need this additional variable “updateUserRequest”? Why do we need a “switchMap” here? In my mind I would just do something like this, when the “continue” button is clicked.
    fun onContinueClicked(firstName: String, lastName: String, phone: String, profileImageUrl: String) {
            mUserBasicDetailsRequestData.value = UserBasicDetailsRequest(firstName, lastName, phone, profileImageUrl)
    
            liveData(<http://Dispatchers.IO|Dispatchers.IO>) {
                emit(NetworkCall<User>(NetworkStatus.LOADING, null, ""))
                val updatedUser = basicDetailsRepository.updateUserBasicDetails(data)
                emit(updatedUser)
            }
        }
    This is of course just a simple example, and I asked it since we repeat this pattern a couple of times. Am I missing some important consideration I might not be aware of?
    m
    • 2
    • 6
  • a

    amar_1995

    02/11/2020, 1:04 PM
    I am trying to use Workmanager to sync local database with server,b ut getting this error.
    java.lang.IllegalStateException: Cannot invoke setValue on a background thread
    override fun doWork(): Result {
        println("Worker is Running >>>> ")
        val database = DatabaseClient.getInstance(applicationContext)
        val server = APIClient.retrofitServiceProvider<ArticleService>()
        val articleRepo = ArticleRepo.getInstance(database, server, applicationContext)
        GlobalScope.launch {
                articleRepo.clearData()
                val data = articleRepo.refreshData(1)
    
        }
        return Result.success()
    }
    Here, I am trying to clean database and then again making a server call which will fetch data from server and load it into local database.
    s
    f
    a
    • 4
    • 12
  • v

    voben

    02/11/2020, 9:28 PM
    In work manager’s doWork function, what scope can we use to run a flow?
    override suspend fun doWork(): Result {
        myFlow.onEach { }.launchIn(//What scope do we use here?)
    }
    n
    s
    s
    • 4
    • 3
  • o

    Ofir Bar

    02/12/2020, 8:43 AM
    Hey guys, Say I have one Activity with a RecyclerView. You can choose items on the RecyclerView. It is important that if the user minimizes the app and gets back to it after hours he still will see the selected items on the RecyclerView. The Activity is forced to be in portrait mode only, set from the manifest using:
    android:screenOrientation="portrait"
    Do I have any good reason to make a ViewModel for this Activity? I know that users can’t rotate the screen. What I am asking, is that in this scenario, do the ViewModel have “higher survival rate” than the Activity?
    s
    t
    a
    • 4
    • 4
  • o

    Ofir Bar

    02/12/2020, 12:04 PM
    May be stupid but a junior dev here 😄 Is there a particular good reason to have a generic function parameter type inherit from “Any”? In the image, the method we use, and the second one is without it.
    d
    w
    a
    • 4
    • 6
  • o

    Ofir Bar

    02/12/2020, 6:13 PM
    I have a generic class NetworkResponse<T>, to wrap any network response:
    /**
     * A class wrapping every network response
     */
    data class NetworkResponse<T>(@SerializedName("code") val code: Int,
                                  @SerializedName("message") val message: String,
                                  @SerializedName("data") val data: T)
    However, I know, for sure, that whenever making a network request to our backend, some network responses will send back a
    NetworkResponse
    with
    data
    equals
    null
    . So then
    T
    cannot be inferred. For example, when we Patch a User data, I receive code 200 OK, but
    data
    object returned is null (no data returned back is expected). Here is the network request using retrofit:
    @PATCH("user")
    suspend fun updateUserBasicDetails(@Body basicDetailsBasicDetailsRequest: UserBasicDetailsRequest) : NetworkResponse<WHAT_TO_DO_HERE?>
    I am not sure what type to set for NetworkRequest in this case. I need to give some object to the NetworkResponse, but don’t want to just put something ugly and unrelated like “String?“. What can be done?
    a
    p
    • 3
    • 2
  • u

    ursus

    02/13/2020, 1:08 AM
    Do you guys put analytics events in a viewmodel or in ui?
    m
    a
    +5
    • 8
    • 17
  • a

    amar_1995

    02/13/2020, 7:44 AM
    Is there any sample project which uses suspend(coroutines), retrofit, room to make get, post, patch and delete request with proper architecture.
    d
    a
    • 3
    • 6
  • u

    ursus

    02/13/2020, 11:19 AM
    How would you share little bits of logic across view models? Lets say function sized - no state
    b
    t
    d
    • 4
    • 8
  • s

    Slackbot

    02/14/2020, 10:23 PM
    This message was deleted.
    v
    u
    • 3
    • 2
  • u

    ursus

    02/15/2020, 3:28 AM
    Given views have shorter lifecycle than viewmodels, how do you handle "transient" errors? If such async request is modeled into a single viewmodel State, or has its own LiveData, and UI wants to show
    Toast
    or error,
    it will re-show the Toast after new view instance is created (after coming back from background, or on rotation), which might be confusing to the user
    m
    s
    t
    • 4
    • 9
  • o

    Ofir Bar

    02/16/2020, 2:56 PM
    Hey guys. What good reads have absolutely changed the way you think about architecture/design? Assuming I am a junior developer, I already know “MVVM”, and I can write big applications, but I find myself writing repeated code. I feel like I am following trends and not having a good understanding of design and best practices. Right now - I am reading effective kotlin, is it the route to go?. What I am worried about is that I see other senior developers being able to write super smart generic code, but I am unsure as if this is something acceptable within the industry or are those “hacks” might get other developers confused or is it just me
    a
    t
    +3
    • 6
    • 15
  • a

    Ahmed Ibrahim

    02/16/2020, 3:31 PM
    Are there any guides out there that discuss state modelling in unidirectional flow architectures? For example:
    // Variant 1
    sealed class MyFeatureState {
        object Loading : MyFeatureState()
        data class Error(val throwable: Throwable) : MyFeatureState()
        data class Items(val items: List<FeatureItem>): MyFeatureState()
    }
    vs
    // Variant 2
    data class MyFeatureState(val isLoading: Boolean = false, val error: Throwable? = null, val items = emptyList<FeatureItem>())
    Which one would be the preferred way to go?
    m
    t
    • 3
    • 4
  • b

    BMG

    02/19/2020, 9:51 AM
    Hi guys, What is the recommended way to use Kotlin interface delegation in Android classes? I use a Fragment and want to "delegate" some portion of logic in that fragment to separate class. This way, I can use Kotlin interface delegation to reduce code in main fragment. Basically,
    class SomeFragment(viewManager: SomeViewManager) : SomeViewInterface by viewManager {
    
    }
    Now I want to pass a
    View
    to
    SomeViewManager
    class. What is the best way to do it? Should I have a setter in
    SomeViewManger?
    i
    g
    a
    • 4
    • 11
  • o

    Ofir Bar

    02/20/2020, 1:49 PM
    Hey guys, how do you manage instances of Firebase Authentication/Firebase Storage? To use Firebase Authentication, I need an instance of
    FirebaseAuth
    and
    StorageReference
    (Firebase Storage). I can only get it from my MainActivity, like the below: `MainActivity.kt`:
    class UploadCertificationActivity : AppCompatActivity() {
        private val mViewModel: UploadCertificationViewModel by viewModel()
        private lateinit var mStorageReference : StorageReference
        private lateinit var mFirebaseAuth : FirebaseAuth
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_profile_upload_certification)
    
            mFirebaseAuth = FirebaseAuth.getInstance()
            mStorageReference = FirebaseStorage.getInstance().getReference(mFirebaseAuth.currentUser!!.uid)
        }
    I’d love to hear how you pass that to your repository and manage that in your projects in general. Please assume I will use that same instance throughout the project. Since right now, I am issues Firebase storage calls directly from my Activity.
    l
    i
    d
    • 4
    • 4
  • j

    Joey

    02/21/2020, 1:54 AM
    Hi guys, just a quick question. If i pass a variable from the model to view via presenter. Does it violate the rules of MVP? Thanks!
    a
    s
    i
    • 4
    • 6
  • l

    Larissa Maraes

    02/27/2020, 10:55 AM
    Guys, in a modular app how can I share a test class between modules? I have a test class which is common to other tests in the project. I've tried to put this class into a "base" module, but I can't import this class in other test classes from another module.
    a
    m
    • 3
    • 4
  • i

    Ianmedeiros

    02/28/2020, 3:50 PM
    Nothing works.
    s
    • 2
    • 14
  • i

    Ianmedeiros

    03/03/2020, 10:17 PM
    Is there any shortcut to bind one object to multiple interfaces with dagger?
    m
    • 2
    • 4
  • u

    ursus

    03/05/2020, 12:29 AM
    val newState = state.copy(
    	items = state.items.map {
    		if (it.id == id) {
    			it.copy(
    				text = newText
    			)
    		} else {
    			it
    		}
    	}
    )
    t
    • 2
    • 4
  • o

    Ofir Bar

    03/10/2020, 8:52 AM
    Hey guys. Regarding the single responsibility pattern, for example when working with Retrofit and Room, I wonder if you have “exceptions” to that rule. I usually fetch data from the network, save it to the local cache, and then the UI gets data from the local DB. However, some parts of my app intensively depends on data from the network, imagine an app like buying and selling stuff like ebay. I expect the data to change frequently. In this case it doesn’t make that sense to cache my data at all, as it might change, so would you feed the UI directly from the network in this case?
    k
    f
    a
    • 4
    • 8
  • j

    Joan Colmenero

    03/10/2020, 6:00 PM
    Hello guys, I'm starting a new project and I'd like to read / discuss with you all your ideas of designing the app. I'm planing to build an app with multi-module, using the clean architecture, so from now I have 1.- app 2.-base_library (contains all the base classes) I could separate it by base_view, base_networking, base_usecase, etc... 3.-login 4.-home 5.-helpdesk etc.... So what do you think having it like this? Is it recomendable? How am I supposed to get for instance login credentials in the helpdesk activity? What do you think using that organisation and don't using core. Is it easy to implement the DI like dagger for such projects?
    f
    • 2
    • 3
  • o

    Ofir Bar

    03/11/2020, 11:19 AM
    How can I make a MutableLiveData that emits values, when the Lifecycle of the UI changes? I tried the following, which isn’t possible:
    r
    • 2
    • 1
  • o

    Ofir Bar

    03/11/2020, 11:21 AM
    Doing the following makes the UI emit values, but once new data is received from the backend, the UI still gets the initialized data:
    k
    • 2
    • 2
  • o

    Ofir Bar

    03/11/2020, 11:22 AM
    Source:
    class MyPublishedAdvertisementsViewModel(private val advertisementRepository : AdvertisementRepository) : ViewModel(){
    
        var _myPublishedAdvertisements : MutableLiveData<NetworkCall<MyPublishedAdvertisementsResponse>> = MutableLiveData()
        val myPublishedAdvertisements : LiveData< NetworkCall<MyPublishedAdvertisementsResponse> > = _myPublishedAdvertisements
    
        // Called every time our UI is #onStarted
        fun getFreshData(){
            _myPublishedAdvertisements.value = liveData {
                emit(NetworkCall<MyPublishedAdvertisementsResponse>(NetworkStatus.LOADING, null, ""))
                val publishedAdvertisements = advertisementRepository.getMyPublishedAdvertisements()
                emit(publishedAdvertisements)
            }
        }
    
    }
    k
    • 2
    • 9
Powered by Linen
Title
o

Ofir Bar

03/11/2020, 11:22 AM
Source:
class MyPublishedAdvertisementsViewModel(private val advertisementRepository : AdvertisementRepository) : ViewModel(){

    var _myPublishedAdvertisements : MutableLiveData<NetworkCall<MyPublishedAdvertisementsResponse>> = MutableLiveData()
    val myPublishedAdvertisements : LiveData< NetworkCall<MyPublishedAdvertisementsResponse> > = _myPublishedAdvertisements

    // Called every time our UI is #onStarted
    fun getFreshData(){
        _myPublishedAdvertisements.value = liveData {
            emit(NetworkCall<MyPublishedAdvertisementsResponse>(NetworkStatus.LOADING, null, ""))
            val publishedAdvertisements = advertisementRepository.getMyPublishedAdvertisements()
            emit(publishedAdvertisements)
        }
    }

}
k

Kirill Prybylsky

03/11/2020, 11:24 AM
Does your NetworkCall extends LiveData?
o

Ofir Bar

03/11/2020, 11:26 AM
No
It is a wrapper data class to be used for all my network responses, this is the code:
data class NetworkCall<out T>(val status: NetworkStatus, val data: T?, val message: String?) {

    companion object {
        fun <T> success(data: T?): NetworkCall<T> {
            return NetworkCall(NetworkStatus.SUCCESS, data, null)
        }

        fun <T> error(msg: String, data: T?): NetworkCall<T> {
            return NetworkCall(NetworkStatus.ERROR, data, msg)
        }

        fun <T> loading(data: T?): NetworkCall<T> {
            return NetworkCall(NetworkStatus.LOADING, data, null)
        }
    }

}
k

Kirill Prybylsky

03/11/2020, 11:27 AM
But you’re putting liveData{} as a value of another live data
o

Ofir Bar

03/11/2020, 11:29 AM
I am not sure what I am doing wrong 🤔
k

Kirill Prybylsky

03/11/2020, 11:32 AM
Seems like you are doing this, isn’t?
Untitled
o

Ofir Bar

03/11/2020, 11:35 AM
Ohhhh, ok I got what you’re saying But I still don’t understand how I use liveData{} to change the values of a MutableLiveData. Why for LiveData I can use liveData{}, and for MutableLiveData I can’t?
k

Kirill Prybylsky

03/11/2020, 11:40 AM
For my opinion you are trying to achieve something completely wrong. You should rethink this code. Also, there shouldn’t be any network requests from your view model class this is bad practice.
o

Ofir Bar

03/11/2020, 11:54 AM
I will check thanks for the help anyway @Kirill Prybylsky
View count: 9