i have to use two fields of `object` in almost eve...
# android
k
i have to use two fields of
object
in almost every activity, so therfore i have to create variables in each activity, i'm creating this variables to just use shorter names nothing else.
Copy code
private val api 
       get() = UserRestApi.instance
   private val authorization
       get() = AccountUtils.userAuthToken
So now my question is that i'm thinking to create
interface
like below.
Copy code
interface Networking {
    val api
        get() = UserRestApi.instance
    val authorization
        get() = AccountUtils.userAuthToken
}
and then in each activity i will implement this interface and then i will directly access this
api
and
authorization
variables. so i don't have to create this variables in each activity, so like below i just have to
implement
Networking
interface and i have access to this variables
Copy code
class MyActivity : AppCompatActivity(), Networking {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.my_activity)
        api.loadSomething(authorization)// so by implementing Networking i can access this fields
    }
}
**1. So is something bad in this approach ? 2. is there any other solution to this problem in kotlin ?**
j
To my mind You should use composition over inheritance in this case, for example you can just create
Networking
object inside the
MyActivity
. Very helpfull can by dependency injection for it.
v
You may also try this way:
Copy code
object Network {
    val api by lazy { UserRestApi.instance }
}
and use it from any activity:
Copy code
Network.api.loadSomething(...)
e
there are bigger architectural issues with this approach. Mainly your activity should not be concerned about Networking and should only focus on presentation and delegate this to some other component (presenter, viewmodel, controler, etc)
👍 8
But if it is a hard requirement that this logic is placed in the activity you should put all that in a collaborator and retrieve them from there (for example as @Vlad suggests)
v
I also think that there may be a bigger issue with the architecture... maybe you should have a
ViewModel
to
launch
network calls in the
viewModelScope
and use
LiveData
to
observe
the result
k
i know you are right about architecture but at this time client does't required a proper architectured app that's why i'm creating network request in Activity, also inside activity i'm using
lifecycleScope
to call network request also i'm using Retrofit with
suspend
functions, i guess this might be enough to handle network request in Activity ?
v
Should be enough, sometimes it is just better to do something straightforward instead of adding more complexity 🙂
💥 1
s
The client really shouldn't be dictating architectures anyway
e
If you are just looking for shorter names use an import alias.