Is it okey to call collect within a Composable - kotlin

I took a look at this tutorial and within it the author explains that making network calls in a composable is a bad habit. But what about getting the results in a StateFlow in a composable is that to a bad habit? Or is that okey? So the question is that when you call collect on a MutableStateFlow is it okey to do that directly in the compose method and not in the a side effect block?

Not only it is not a bad habit, it is the only way to actually use the result in composable. I wouldn't expose MutableStateFlow but rather only StateFlow, but the rest is just fine

Related

Should initialisation of class-level variable with by lazy in Kotlin be avoided because it prevents Unit Testing?

Having a class-level variable and instantiating the object at the same time creates a problem for Unit Testing because you can't really mock the dependency.
Does this mean the Kotlin feature by lazy should be avoided as it hinders proper unit testing, or is there a way to overcome this? Thanks.
A lazy is just a val that gets initialised later - if you need to change all your vals to vars so you can poke around at them while testing, that's probably a bad sign.
If your lazy is creating objects, then that's where dependency injection comes in - pass in the dependency, or something that provides the dependency, and then you can mock that when the lazy initialiser calls it.
If you're just trying to change the internal state so you can test a particular scenario, that's trickier. Ideally with a unit test you're testing the behaviour of a single component, and how it interacts with other things - if it provides the expected input and output. You shouldn't need to poke around at the internals, at least not in a way that isn't already part of the design and part of the expected use case.
But sometimes you want to recreate state, which is possible using the normal API, but takes a lot of code. That's a trickier call when the component isn't already designed that way - if it's that important, you might want to make it configurable, either through constructor parameters or by passing in some kind of config object.
Making things public that should be private just for testing is usually a sign that you should find another way to do your test. Changing a val to a var just for testing is especially bad, because it breaks the usual immutability guarantees and now your code has to handle all the "possibly changed" warnings even though you know it's really a val. I don't think lazy really makes much difference here - it's just a fancy getter, an internal implementation detail. I think your issues are more down to how the code is structured, and injecting your dependencies will probably help a lot

In which cases you don't want or you shouldn't use coroutines in Kotlin?

I'd read a lot of the many adventages of using coroutines, but I find nothing about why you shouldn't or couldn't use them.
Why not use all methods as suspend methods, by the way?
I'm having some trouble to understand some concepts here, so with my question I pretend to make the opposite case (why not use it), so I can understand better by contrast.
The main reason not to have all functions suspendable is the overhead they introduce, at least on the JVM. Every suspendable function compiles into a Java method that receives another parameter, the continuation object, and its body compiles into pretty complex state machine code that, among other things, always instantiates another continuation object and daisy-chains it to the one received as the parameter.
So, whenever you have nothing to gain from coroutines, you shouldn't use them as the default way to do things.
Please see my answers inline to your questions:
but I find nothing about why you shouldn't or couldn't use them.
Answer:
a. You should not use them for any foreground task.
b. You should not use them for any simple/real quick operations.
c. You should not use them for any kind of initialization.
Why not use all methods as suspend methods, by the way?
Answer:
a) This will be treated as code smell. Bad practice to do so.
b) If you mark all functions as suspend, then whenever you want to call a suspend function you will have to create a Coroutine Scope to run it.
c) Testing of suspend function is difficult. It needs some additional setup of RunBlockingTest from AndroidX.

Kotlin basics : RatingBar, listeners

I started learning Kotlin few weeks ago and I need help understanding the basics.
What is a listener? For example, what is RatingBar's listener? How do I find a listener of other widgets?
What are the parameters? Again, what is RatingBar's parameters? How do I find the parameters of other widgets?
What is View.____?
If you're writing a component that handles events of some kind, you'll probably want a way to inform other components about those events. There are lots of ways to do this (in a software design sense), and one of those is the idea of a listener.
The basic idea is that components can register themselves as listeners, and when a relevant thing happens, they get a callback. The component generating the events doesn't need to know what those listeners are, it just needs to hold a reference to one (or more) and call some callback function when the event happens. The key thing here is that the component doesn't have a listener, you have to provide them. You're hooking components up.
So a typical way to do this is for a component to implement a callback interface, which basically says "I have a function called this with these parameters" and the event component can just call that function with the details when an event happens. You could also create an object that implements that interface, or in Kotlin's case you can just pass a function in that matches the signature of the callback function - basically providing a block of code that says "when the event happens, do this stuff in response". That's typically how you define behaviour, like setting an on-click listener - you write a block of code to execute when the user clicks a thing, and when the event happens, that code gets run.
I hope that makes sense generally - if any of it's confusing (since you're new) I'd recommend reading the basic trails in the Java Tutorials (which Kotlin is based on) to get a handle on interfaces and the like.
As for the other questions... if you're asking what the parameters are when you construct a RatingBar or whatever, the best place to look is the documentation (although you generally won't be constructing Views in code anyway, just adding them to a layout XML file) - Android Studio should pop up some hints too (you can hit ctrl+q for documentation on the thing your cursor is currently over, or ctrl+p for parameter hints).
If you're asking what a View is, it's the base class for Android's UI components, it's really anything that's able to draw itself and be included in a layout. It has a lot of methods because it has a lot of functionality built in to handle all these UI responsibilities.
If you're asking what View.something is, that's a static method or field defined on the View class - if you don't know what that means, read the Java tutorial link I included! You'll typically be referencing things like View.VISIBLE which is a set value you provide to a View's setVisibility method - it knows what those values mean and what to do with them

Why is CoroutineScope.launch and Coroutine.async are extension functions instead of a member function of CoroutineScope?

The title states my question.
What is exactly the reason why CoroutineScope.launch and Coroutine.async are just extension functions of CoroutineScope instead oa a member function?
What benefits does it provide?
I am asking because maybe the reason behind this design could be helpful in designing things in the future too.
Thank in advance.
Mostly because with extension functions it is easier to structure your code in multiple modules even if it is represented as one class.
CoroutineScope is actually a really good example of this design pattern. Take a look at CoroutineScope.kt where the interface is declared. There is only basic functionality there (plus operator and cancel())
The two functions you mentioned are defined in Builders.common.kt. If You take a look at the contents of this file, you can see that there are multiple classes which are private, this means they can only be used in this file. This tells you right away that you don't need this these classes for the basic functionality which is designed in CoroutineScope.kt, they are only there for launch {...} and async {...}
So if you have a large class with multiple functionality, it makes sense to break it up in multiple files (=modules).
launch and async are coroutine builders, but they aren't the only ones: look in integration modules for future (and another future), publish, the RxJava 2 builders etc. Obviously those can't be members of CoroutineScope, so why should launch and async be?
In addition, by being extension functions you know they don't rely on any CoroutineScope privates (well, they could rely on internals since they are in the same module).
The kotlinx.coroutines uses structural concurrency approach to make sure all errors are propagated to a parent coroutine. Similarly, a parent coroutine will by default wait for all it's child coroutines to complete.
There is a Job object associated with every coroutine when you do launch or async. It is just easier to use extension functions for that design to make it work implicitly, without a code-writer explicit attention
You may have a look at the more detailed explanation :
https://kotlinlang.org/docs/reference/coroutines/basics.html#structured-concurrency
https://medium.com/#elizarov/structured-concurrency-722d765aa952

Should API return CompletionStage or CompletableFuture

When building an API it is a good practice to code to an interface so it seems like returning CompletionStage seems like a best approach. However I realized that I happen to be always calling .toCompletableFuture after getting the CompletionStage. What is the recommended approach in this case?
See my reply at https://stackoverflow.com/a/49158702/1113842
Like Holger asked, why do you call toCompletableFuture?
Do you want to the caller to complete/cancel it? Most applications provide their own mechanisms for completing the stage. Thus, it's not necessary to expose these methods.
Do you want to use the blocking get? This should be avoided in async programming.
If the answers are no to both questions, you should return CompletionStage.
An API using the CompletionStage is meant for non-blocking use, so the call .toCompletableFuture() is only required if the caller does not work in non-blocking way.
If the API is not non-blocking, it should return plain old Future interface.