Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of RXJava map in Kotlin?

Why is this complaining about a miss-type? map supposed to transfor the value of an observable to another, but it's expecting me to return an observable from the map

override fun fetchExercises(): Observable<List<Exercise>> {
    return FirebaseDatabase.getInstance()
        .getReference("exercises")
        .observeSingleEvent()
        .map { snapshot: DataSnapshot? -> object: List<Exercise>
            // Error here
            return listOf<Exercise>()
        }
    }

fun DatabaseReference.observeSingleEvent(): Observable<DataSnapshot> {
    return Observable.create(object : Observable.OnSubscribe<DataSnapshot> {
        override fun call(subscriber: Subscriber<in DataSnapshot>) {

            val valueEventListener = object: ValueEventListener {
                override fun onDataChange(snapshot: DataSnapshot?) {
                    subscriber.onNext(snapshot)
                    subscriber.onCompleted()
                }

                override fun onCancelled(error: DatabaseError?) {
                    subscriber.onError(FirebaseDatabaseThrowable(error))
                }
            }

            addListenerForSingleValueEvent(valueEventListener)
        }
    })
}
like image 561
aryaxt Avatar asked Dec 19 '22 05:12

aryaxt


1 Answers

@zsmb13 has pointed out the correct answer right there. Here, I would like to comment on some mistake made in your lambda expression.

.map { snapshot: DataSnapshot? -> object: List<Exercise>
        // Error here
        return listOf<Exercise>()
}

object: List<Exercise> here is not a valid syntax since the body goes after an -> sign inside the lambda expression. We do not specify the return type inside the body.

Also, the return here means to return from fetchExercises() as described in Kotlin docs:

A return statement without a label always returns from the function declared with the fun keyword. This means that a return inside a lambda expression will return from the enclosing function, whereas a return inside an anonymous function will return from the anonymous function itself.

As what @zsmb13 said, return is not needed in most of the case. If you really want it(for flow control), you can use qualified returns:

//This is answer from @zsmb13
.map { snapshot: DataSnapshot? ->
    return@map listOf<Exercise>()
}
like image 95
BakaWaii Avatar answered Jan 09 '23 10:01

BakaWaii