https://kotlinlang.org logo
#coroutines
Title
# coroutines
a

alexfacciorusso

10/18/2019, 10:37 AM
This is something I came up:
Copy code
private val _state = liveData<LoginViewState> {
        coroutineScope {
            launch {
                usernamePasswordChannel.consumeEach { (username, password) ->
                    validateLoginDataUseCase.validateLoginData(
                        username,
                        password
                    ).perform(latestValue!!).also { emit(it) }
                }
            }
            launch {
                isLoggingInChannel.consumeEach {
                    usernamePasswordChannel.value.let { (username, password) ->
                        performLoginUseCase.login(
                            username,
                            password
                        )
                    }.perform(latestValue!!).also { emit(it) }
                }
            }
        }
    }
It looks a bit odd, has anyone any suggestion about something I’m misusing or that can be optimised in terms of code?
m

marstran

10/18/2019, 10:39 AM
I think you can use
select
to read from both channels without having consume them in two launch-tasks.
d

Dominaezzz

10/18/2019, 10:48 AM
You can use
asFlow
on the
BroadcastChannel
and
consumeAsFlow
on the
Channel
. Then use flow operators to combine them.
a

alexfacciorusso

10/18/2019, 10:54 AM
and then consume the final flows in the live data block itself?
also, how would you transform a Flow in a way the logic would make sense in the same way as the one I wrote with coroutines?
d

Dominaezzz

10/18/2019, 11:09 AM
Like,
Copy code
usernamePasswordChannel.asFlow().map { (username, password) ->
   validateLoginDataUseCase.validateLoginData(
                        username,
                        password
                    ).perform(latestValue!!)
}
?
a

alexfacciorusso

10/18/2019, 11:09 AM
yes, that part make sense, indeed it’s what I tried to write, but the real problem is when I have to combine username and password AND the Unit when I press the login button 😄
the logic would be: whenever usernamePasswordChannel, the state changes using the data validator usecase, and when isLoggingInChannel is changed, it gets combined with usernamePasswordChannel and the proper login performs
d

Dominaezzz

10/18/2019, 11:20 AM
the state changes using the data validator usecase
Where is this in your code?
a

alexfacciorusso

10/18/2019, 11:21 AM
`validateLoginDataUseCase.validateLoginData(...)`is when the data is validated, and
performLoginUseCase.login(...)
is when the login is performed
a

Adam Powell

10/18/2019, 1:20 PM
You probably don't want consume for the channels since it will ensure the channel is closed when those blocks exit. You want this LiveData to be able to become active/inactive multiple times.
3 Views