By your explanation and your final question I see two scenarios. And without seeing your code just to make abstract examples, so come on.
First scenario: Observables working with methods
To pass "methods" on Observable
, you will have to create a class or interface that declares this method and use it. In the same way that would be done without Observable.
Example with Callable
:
// Type could be something else
Callable<String> callHello = new Callable<String>() {
@Override
public String call() throws Exception {
// Could be a db query, api call...
return "Hello";
}
};
Callable<String> callWorld = new Callable<String>() {
@Override
public String call() throws Exception {
return "World";
}
};
The type of the first Observable would be Callable<String>
, as follows:
Observable.just(callHello, callWorld)
.map(new Function<Callable<String>, String>() {
@Override
public String apply(Callable<String> callable) throws Exception {
return callable.call();
}
})
.subscribe(new Consumer<String>() {
@Override
public void accept(String x) throws Exception {
System.out.println(x);
}
});
An example with a repository of Model
I declare the contract:
interface ModelRepository<T extends Model> {
List<T> listModels();
}
I have two classes that obey this contract.
A search User
(extending Model
):
class UserRepository implements ModelRepository<User> {
@Override
public List<User> listModels() {
return userDAO.list();
}
}
Another search Event
(which also extends Model
):
class EventRepository implements ModelRepository<Event> {
@Override
public List<Event> listModels() {
return eventDAO.list();
}
}
Observable then starts with repositories and ends with two lists of Model
Observable.just(userRepository, eventRepository)
.map(ModelRepository::listModels)
.subscribe(listOfModels -> {/* do something with List<Model> */});
In both cases I am passing an object that implements a method declared in the interfaces (call
and listModels
).
Second scenario: Engage existing Apis in Observables.
For blocking methods the simplest way is by using the fromCallable
:
Observable.fromCallable(() -> blockingGetUserFromRemote())
.flatMap(user -> Observable.fromCallable(() -> blockingSaveUserToLocal(user)))
.subscribe(saveResult -> { /* Do something with save result */ });
In this case I have two blocking methods: blockingGetUserFromRemote
searching for a user on a web service and blockingSaveUserToLocal
that saves the user in the bank. With the fromCallable
it is possible to involve them in a Callable
and use them in a non-blocking way.
To turn listeners into Observables, I recommend seeing the source code of some library that does this (Rxbinding, for example). It is a little more complex and long.