'Wait until the callback returns a non empty response or the
timeout fires.'

@defer.inlineCallbacks
def wait_for_events(self, user_id, timeout, callback, room_ids=None, from_token=StreamToken.START):

    user_stream = self.user_to_user_stream.get(user_id)
    if (user_stream is None):
        current_token = (yield self.event_sources.get_current_token())
        if (room_ids is None):
            room_ids = (yield self.store.get_rooms_for_user(user_id))
        user_stream = _NotifierUserStream(user_id=user_id, rooms=room_ids, current_token=current_token, time_now_ms=self.clock.time_msec())
        self._register_with_keys(user_stream)
    result = None
    prev_token = from_token
    if timeout:
        end_time = (self.clock.time_msec() + timeout)
        while (not result):
            try:
                now = self.clock.time_msec()
                if (end_time <= now):
                    break
                listener = user_stream.new_listener(prev_token)
                with PreserveLoggingContext():
                    (yield self.clock.time_bound_deferred(listener.deferred, time_out=((end_time - now) / 1000.0)))
                current_token = user_stream.current_token
                result = (yield callback(prev_token, current_token))
                if result:
                    break
                prev_token = current_token
            except DeferredTimedOutError:
                break
            except defer.CancelledError:
                break
    if (result is None):
        current_token = user_stream.current_token
        result = (yield callback(prev_token, current_token))
    defer.returnValue(result)
