J
J
JZX2021-08-29 13:26:23
Android
JZX, 2021-08-29 13:26:23

Why is the copy function constantly used in reactive approaches?

Very often on this forum I see recommendations regarding the processing of responses in Rx chains, where they write that it is necessary to minimize state changes and for this it is necessary to use the kotlin copy function.
Now I am in the process of learning and have not yet written complex applications. Can you explain with some simple example what problems can arise if this is not done?

I don't understand the advantages of using copy over directly accessing setters and setting values ​​through them.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2021-08-29
@JZX

The advantage is that when using immutable objects, the data flow remains unidirectional. And if you mutate objects, hellish special effects can happen. For example.

data class Data(var x : Int)

Observable.just(1, 1, 2, 2)
    .doOnNext { print("I'm $it") }
    .map(::Data)
    . distinctUntilChanged()
    .map{
       it.apply{ x++ }
    }
    .doOnNext { print("Now I'm $it") }
    .subscribe()

What will it print? You can’t say it right off the bat, you have to think about it. And what behavior was expected by the author of such code? Unclear. And this is a primitive chain, imagine what kind of tin can happen in a more difficult situation.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question